平衡二叉树判断

59 篇文章 0 订阅
54 篇文章 0 订阅

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

解法一:递归实现(需要重复遍历节点多次)

import java.util.*;

/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class CheckBalance {
    public boolean check(TreeNode root) {
        // write code here
        if(root==null){
            return true;
        }
        int lh=getDepth(root.left);
        int rh=getDepth(root.right);
        int diff=lh-rh;
        if(diff>1||diff<-1){
            return false;
        }
        return check(root.left)&&check(root.right);
    }
    //返回一个节点的深度,即该节点到叶子节点的路径最大长度
    private int getDepth(TreeNode root){
        if(root==null){
            return 0;
        }
        int lh=getDepth(root.left);
        int rh=getDepth(root.right);

        return lh>rh?(lh+1):rh+1;
    }
}

解法二:

import java.util.*;
 
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
public class CheckBalance {
    public boolean check(TreeNode root) {
        //定义一个引用类型的数据作为平衡标记,通过传引用的方式在递归左右子树时修改平衡标记
        boolean[] res=new boolean[1];
        //从根节点开始遍历树,遍历过程中修改平衡标记
        res[0]=true;
        postCheck(root,1,res);
         
        return res[0];
    }
    public int postCheck(TreeNode root,int depth,boolean[] res){
        if(root==null){
            return depth;
        }
        //遍历一次左子树,获取深度(深度已经在参数改变了,目的是为了检查左子树是否平衡)
        //若遍历左子树过程中修改了平衡标记为false,则子树非平衡,所以当前结点为根的子树非平衡,不再递归,直接返回

        int left_depth=postCheck(root.left,depth+1,res);
        if(res[0]==false){
            return depth;
        }
        //若左子树是平衡的,则遍历右子树并获取深度
        //若遍历右子树过程中修改了平衡标记为false,则子树非平衡,所以当前结点为根的子树非平衡,不再递归,直接返回
        int right_depth=postCheck(root.right,depth+1,res);
        if(res[0]==false){
            return depth;
        }
         
        //若左右子树都是平衡的,则对左右子树深度进行比较,判断当前结点为根的子树是否平衡
        if(Math.abs(left_depth-right_depth)>1){//高度差大于1,当前子树不平衡,修改平衡标记
            res[0]=false;
        }
        //用左右子树深度最大者作为自己的高度
        return Math.max(left_depth,right_depth);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值