二叉树--判断平衡二叉树

判断一棵树是不是平衡二叉树,平衡二叉树的定义就是,左右子树的差的绝对值不超过1,其实也就是求解出每个节点的左右子树的深度差。

代码如下:

public boolean isBalanced(TreeNode root) {
    if (root == null) return true;
    if(!isBalanced(root.left)) return false;
    if (!isBalanced(root.right)) return false;
    return Math.abs(depth(root.left) - depth(root.right)) <=1;

}

public static int depth(TreeNode root) {
    if (root == null) return 0;
    int depth = Math.max(depth(root.left), depth(root.right)) +1;
    return depth;
}
public boolean isBalanced(TreeNode root) {
        return checkBalance(root) == -1 ? false : true;
    }

    // 1. If a subtree is hit as unbalanced, the whole tree is unbalanced. In this case, -1 is set as the return value.
    // 2. If the left subtree and the right subtree of a node are balanced, there are two more cases:
    // 2.1. The tree rooted at the node is unbalanced (the depth of its two subtrees differs by more than 1), as a result, -1 is returned.
    // 2.2 The tree rooted at the node is balanced, then the depth of the tree will be returned.
    public int checkBalance(TreeNode node){
        if (node == null) // case 2.2
            return 0;

        int left = checkBalance(node.left);
        if (left == -1) // check case 1
            return -1;

        int right = checkBalance(node.right);
        if (right == -1) // check case 1
            return -1;

        if (left - right > 1 || right - left > 1)
            return -1; // check case 2.1

        return (left > right ? left : right) + 1; // case 2.2
    }

非递归代码:
也就是对求解树的每个节点的深度进行非递归的操作,不多说了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值