平衡二叉树

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

在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树

错误做法,对平衡二叉树的理解出现了偏差,平衡二叉树判断其是否平衡,是判断每个中间节点的左右子树高度差是否小于等于1,而不是对所有叶子节点的位置作比较.

public class Solution {
    int max_depth=-1,min_depth=10000;
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)return true;
        isBaleance(root,1);
        return max_depth-min_depth<=1;
    }
    public void isBaleance(TreeNode root,int depth){
        if(root.left==null&&root.right==null){
            min_depth=Math.min(min_depth,depth);
            max_depth=Math.max(max_depth,depth);
            return;
        }
        isBaleance(root.left,depth+1);
        isBaleance(root.right,depth+1);
        return;
    }
}

理解平衡二叉树后,可通过递归遍历整棵树的方式判断是否平衡.
问题:这种做法有很明显的问题,在判断上层结点的时候,会多次重复遍历下层结点,增加了不必要的开销。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null)return true;
        return Math.abs(getDepth(root.left)-getDepth(root.right))<=1&&
            IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
    }
    public int getDepth(TreeNode root){
        if(root==null)return 0;
        return Math.max(getDepth(root.left),getDepth(root.right))+1;
    }
}

改进:如果改为从下往上遍历,如果子树是平衡二叉树,则返回子树的高度;如果发现子树不是平衡二叉树,则直接停止遍历,这样至多只对每个结点访问一次。

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return getDepth(root)!=-1;
    }
    public int getDepth(TreeNode root){
        if(root==null)return 0;
        int left=getDepth(root.left);
        if(left==-1)return -1;
        int right=getDepth(root.right);
        if(right==-1)return -1;
        return Math.abs(left-right)>1?-1:1+Math.max(left,right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值