【题55】 二叉树的深度 平衡二叉树

【题目一】
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
【思路】
如果一棵树只有一个节点,那么它的深度是1.
如果根节点只有左子树没有右子树,左子树深度加1.
如果根节点只有右子树没有左子树,右子树深度加1.
如果既有左子树也有右子树,较大值加1.
【代码】

/**
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;
        int nLeft = TreeDepth(root.left);
        int nRight = TreeDepth(root.right);
        int depth = nLeft>nRight?(nLeft+1):(nRight+1);
        return depth;
    }
}

【题目二】
输入一棵二叉树,判断该二叉树是否是平衡二叉树。任意节点左子树右子树深度相差不超过1.
【思路】
后序遍历二叉树每个节点,在遍历到每个节点之前就已经遍历了它的左右子树,只要在每个节点的时候记录它的深度(某一点的深度等于它到叶子节点的路径长度)
【实现】

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        if(Math.abs(getHeight(root.left)-getHeight(root.right))>1) return false;
        return IsBalanced_Solution(root.left) &&IsBalanced_Solution(root.right);
    }
    public int getHeight(TreeNode root){
        if(root == null) return 0;
        return max(getHeight(root.left),getHeight(root.right))+1;
    }
    private int max(int a ,int b){
        return (a>b)?a:b;
    }
}

参考:
1.《剑指offer》

猜你喜欢

转载自blog.csdn.net/weixin_39795049/article/details/88687276