1. 遍歷問題 Preorder / Inorder / Postordernode
preorder: root left rightpython
inorder: left root rightide
postorder: left right rootpost
遇到二叉樹的問題,就是一步步的拆分,最經常使用的就是Divide & Conquer的遞歸實現this
貼一個preorder的例子spa
Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: Preorder in ArrayList which contains node values. """ def preorderTraversal(self, root): result = [] if root is None: return result result = [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right) return result
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: An integer """ def maxDepth(self, root): depth = 0 if root is None: return depth depth = max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 return depth
3. 繼續進行延伸,在Balanced binary tree 的作法中能夠應用 maxDepth的解法blog
判斷是不是balanced binary tree最直觀的就是左右子樹的高度差,對任意一個點來講的話 left - right > 1 則不是balanced遞歸
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def maxDepth(self, root): if root is None: return 0 left = self.maxDepth(root.left) right = self.maxDepth(root.right) # at first, the abs is ignored and the operations when the maxdepth is calculated is wrong if left == -1 or right == -1 or abs(left - right) > 1: return -1 return max(left, right) + 1 def isBalanced(self, root): if root is None: return True return self.maxDepth(root) != -1