判断是否为平衡二叉树


题目:如标题所示。

链接:https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tqId=11192&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

 

Code如下:

 

public class Solution {
    //后续遍历时,遍历到一个节点,其左右子树已经遍历  依次自底向上判断,每个节点只需要遍历一次
     
    private boolean isBalanced=true;
    public boolean IsBalanced_Solution(TreeNode root) {
         
        getDepth(root);
        return isBalanced;
    }
    public int getDepth(TreeNode root){
        if(root==null)
            return 0;
        int left=getDepth(root.left);
        int right=getDepth(root.right);
         
        if(Math.abs(left-right)>1){
            isBalanced=false;
        }

        // left,right是对当前节点的左右子节点进行遍历,return Math.max(left,right)+1
         // 则是求出当前节点的深度,并将结果抛给上一层。
        // 这三个步骤相结合则是一次后序遍历(左右根)
        return right>left ?right+1:left+1;
         
    }
}

 

posted @ 2019-07-28 22:30  知事  阅读(167)  评论(0编辑  收藏  举报