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