LeetCode110 平衡二叉树

  1. 题目
    给定一个二叉树,判断它是否是 平衡二叉树
  2. 示例
    示例 1:
    输入:root = [3,9,20,null,null,15,7]
    输出:true
    
    示例 2:
    输入:root = [1,2,2,3,3,null,null,4,4]
    输出:false
    
    示例 3:
    输入:root = []
    输出:true
  3. 解题思路
    1. 平衡二叉树 是指该树所有节点的左右子树的深度相差不超过 1。
    2. 方法一:根据平衡二叉树的概念,递归每一个节点其左右子树的深度,判断是否平衡。
    3. 方法二:方法一的优化,减少递归次数。当遇到不是平衡二叉树的节点直接返回,不在继续递归。
  4. 代码(Java)
    // 方法一
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if (root == null) {
                return true;
            }
            if (root.left == null && root.right == null) {
                return true;
            }
            return isBalanced(root.left) && isBalanced(root.right) && (Math.abs(deep(root.left) - deep(root.right)) <= 1);
        }
        
        public int deep(TreeNode root) {
            if (root == null) {
                return 0;
            }
            return Math.max(deep(root.left), deep(root.right)) + 1;
        }
    }
    // 方法二
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if (root == null) {
                return true;
            }
            if (root.left == null && root.right == null) {
                return true;
            }
            return deep2(root) != -1;
        }
    
        public int deep2(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int left = deep2(root.left);
            int right = deep2(root.right);
            if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
                return -1;
            }
            return Math.max(left, right) + 1;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值