110. Balanced Binary Tree

Balanced binary tree是左子数和右子树的高度最大差一。所以检查用递归是最方便的。
注意在平衡的子树时,要返回max(left_height, right_height)+1

    def isBalanced(self, root: TreeNode) -> bool:
        def helper(root):
            # first a recursive solution
            if root == None:
                return (0, True)
            else:
                left_height, left_balanced = helper(root.left)
                right_height, right_balanced = helper(root.right)
                if not left_balanced or not right_balanced:
                    return (left_height, False)
                if abs(left_height-right_height)>1:
                    return (left_height, False)
                return (max(left_height,right_height)+1, True)
        (h, balanced) = helper(root)
        return balanced

试着做下iterative。
比较难了。需要做post-order iterative traversal
好处是因为是后序,知道了它两个子节点的height,就可以做比较了,然后把本节点的height update一下。
不过不知道如何来保存height。原题目里面不可以保存。难不成要把树copy一份?

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.height = -1

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        # iterative (post-order traversal)
        stack = []
        cur = root
        pre = None
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack[len(stack)-1]  # top operation
            if not cur.right or cur.right == pre:
                if not cur.right:
                    if not cur.left:
                        cur.height = 1
                    else:
                        if cur.left.height > 1: 
                            return False
                        cur.height = cur.left.height+1
                else:
                    left_height = cur.left.height
                    right_height = cur.right.height
                    if abs(left_height - right_height)>1: 
                        return False
                    cur.height = max(left_height, right_height) + 1
                stack.pop()
                pre = cur
                cur = None
            else:
                cur = cur.right
        return True 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值