面试题:平衡二叉树

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

思路:利用上一题求二叉树的深度

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null) return true;
        int left=depth(root.left);
        int right=depth(root.right);
        int balance=left-right;
        if(balance>1||balance<-1)
            return false;
        else
            return true;
    }
    public int depth(TreeNode root){
        if(root==null) return 0;
        int left=depth(root.left);
        int right=depth(root.right);
        return left>right?(left+1):(right+1);
    }
}

 

posted on 2018-08-26 10:35  Aaron12  阅读(291)  评论(0编辑  收藏  举报

导航