平衡二叉树

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
写一个函数返回左右子树的深度,然后判断。
public class Solution {    
    //判断根节点左右子树的深度,高度差超过1,则不平衡    
    public boolean IsBalanced_Solution(TreeNode root) {        
        if (root==null) {            
            return true;        
        }        
        int left = getTreeDepth(root.left);        
        int right = getTreeDepth(root.right);        
        return Math.abs(left-right)>1?false:true;    
    }        
    //求取节点的深度    
    public static int getTreeDepth(TreeNode root) {        
        if (root==null) {            
            return 0;        
        }        
        int leftDepth = 1+getTreeDepth(root.left);        
        int rightDepth = 1+getTreeDepth(root.right);        
        return leftDepth>rightDepth?leftDepth:rightDepth;    
    }
}

 

posted @ 2017-03-02 09:24  alittlecomputer  阅读(141)  评论(0编辑  收藏  举报