第38题:二叉树的深度

难易度:⭐

题目描述:

输入一棵二叉树,求该树的深度。
从根结点到叶结点依次经过的结点形成树的一条路径,最长路径的长度为树的深度。

本题的思路很简单,自然而然就可以想到递归求解,代码如下:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        
        if(root.left == null && root.right == null){
            return 1;
        }else if(root.left != null && root.right == null){
            return TreeDepth(root.left) + 1;
        }else if(root.left == null && root.right != null){
            return TreeDepth(root.right) + 1;
        }else{
            return Math.max(TreeDepth(root.left),TreeDepth(root.right)) + 1;
        }
    }
}

第39题:判断一棵树是否是平衡二叉树

难易度:⭐⭐

题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。

什么是平衡二叉树?
平衡二叉树对任意一个节点来说,左子树与右子树的高度差不会超过1
例如:


image.png

对该树而言,这棵树的任意一个节点的左子树和右子树的高度差不大于1,所以这棵树是一棵平很二叉树。
本题需要判断一棵树是否为平衡二叉树,解题思路如下:

如果这棵树是一棵平衡二叉树,那么对任意一个节点来讲
1.左子树是一棵平衡二叉树
2.右子树是一棵平衡二叉树
3.左子树和右子树的高度差小于等于1

本题从宏观的角度去思考,应用了递归的思想,代码如下:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return isBalanced(root);
    }
    
    public static boolean isBalanced(TreeNode root){
        return getBalancedHeight(root).getHeight() != -1;
    }
    
    public static class BalancedHeight{
        private int balancedHeight;
        
        public BalancedHeight(int h){
            this.balancedHeight = h;
        }
        
        public int getHeight(){
            return this.balancedHeight;
        }
    }
    
    public static BalancedHeight getBalancedHeight(TreeNode node){
        if(node == null){
            return new BalancedHeight(0);
        }
        int leftTreeHeight = getBalancedHeight(node.left).getHeight();
        int rightTreeHeight = getBalancedHeight(node.right).getHeight();
        if(leftTreeHeight == -1 || rightTreeHeight == -1){
            return new BalancedHeight(-1);
        }
        if(Math.abs(leftTreeHeight - rightTreeHeight) > 1){
            return new BalancedHeight(-1);
        }
        return new BalancedHeight(Math.max(leftTreeHeight,rightTreeHeight) + 1);
    }
}