解二叉树的很多问题都是遍历,前序遍历只能得到前面节点的信息,而后序可以得到子节点的信息
前序,需要多次调用
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def depth(root):
if not root:
return 0
return max(depth(root.left),depth(root.right))+1
if not root:
return True
return abs(depth(root.left)-depth(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)
后序,减少调用次数
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def depth(root):
if not root:
return 0
left_h = depth(root.left)
right_h = depth(root.right)
if left_h == -1 or right_h == -1 or abs(left_h - right_h)>1:
return -1
return max(left_h,right_h)+1
return depth(root) >= 0