判断平衡二叉树

方法一:

依次判断每个结点的左右子树高度,使用一个获取二叉树深度的递归函数:

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if (root == null){
            return true;
        }
        int count = Math.abs(TreeDepth(root.left) - TreeDepth(root.right));
        return count <= 1 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
    }

    public int TreeDepth(TreeNode root) {
        int left = 0, right = 0;
        if (root == null){
            return 0;
        }else {
            left = TreeDepth(root.left);
            right = TreeDepth(root.right);
            return Math.max(left,right) + 1;
        }
    }
}

存在的问题:先序遍历会对结点进行重复访问

方法二:

使用后序遍历,从下往上遍历,如果子树是平衡的则返回子树高度,如果子树不平衡,那么直接返回-1(代表不平衡)

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return TreeDepth(root) != -1;
    }

    public int TreeDepth(TreeNode root) {
        int left = 0, right = 0;
        if (root == null){
            return 0;
        }else {
            left = TreeDepth(root.left);
            if (left == -1){
                return -1;
            }
            right = TreeDepth(root.right);
            if (right == -1){
                return -1;
            }
            return Math.abs(left - right) > 1 ? -1 : 1 + Math.max(left,right);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值