Tree110BalancedBinaryTree

6 篇文章 0 订阅
4 篇文章 0 订阅

Attention

the definition of “balanced” here is for “the depths of the two sub trees”, not “the depths of all the leaves”.

思路

  • Level Traversal, check the number of each level equals 2^height Or not. Failed Case 2
    • Actually it is ’ the depths of all leaves’ as Attention listed.
  • Fine the node that ‘made’ the differ of height
    • If one of its child is null, check its child’s child exist or not.
    • Logic is wrong. See Fail Case 1
  • Return the height of each child.
    • Check itself is balanced and check its child
    • Recursive one takes 3ms
    • Actually we can use non-recursive one. The only reason to use it is because —– The “raw content”干货 of this function is very small, just comparing the height of two sub-trees.

Failed case

  1. 只考虑了difference在同一个节点的情况,没考虑不同节点。思路2不正确

    Input: [1,2,2,3,3,null,null,4,4]
    Output: true
    Expected: false
  2. 思路1也不正确,并没有真正读题,以下情况应该返回1

    Input:[1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]
    Output:false
    Expected:true

    Failed Test Case[1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]

TIPS

  • 一旦看到IfElse的return很简单,可以写成?:形式,这样比较简明,不然太繁杂
  • 叠加的else可以简化

Original getDepth()

private static int getDepth(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = getDepth(root.left);
        //If the left child is balanced, we search the other one
        if (leftDepth != -1) {
            int rightDepth = getDepth(root.right);
            //If the right child is balanced
            if (rightDepth != -1) {
                if (Math.abs(leftDepth - rightDepth) > 1 ) {return -1;}
                else { return 1 + Math.max(leftDepth, rightDepth);}
            } else {
                return -1;//This can be simplized in the end of the function.
            }
        } else {
            return -1;
        }
    }

简化后为

    private static int getDepth(TreeNode root) {
        if (root == null) return 0;
        int leftDepth = getDepth(root.left);
        //If the left child is balanced, we search the other one
        if (leftDepth != -1) {
            int rightDepth = getDepth(root.right);
            //If the right child is balanced
            if (rightDepth != -1) {
                return Math.abs(leftDepth - rightDepth) > 1 ?  -1 :  1 + Math.max(leftDepth, rightDepth);
            }
        }
        return -1;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值