今天覆習了下二叉樹的基礎知識。node
有二叉樹以下:python
# node樹節點 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # 經過list建立二叉樹, 遞歸方式 def createTree(nums, i): if i < len(nums): node = TreeNode(nums[i]) node.left = createTree(nums, 2 * i + 1) node.right = createTree(nums, 2 * i + 2) return node # 經過list建立二叉樹, 循環方式 def createTree(nums): if not nums: return None root = TreeNode(nums[0]) node_queue = [root] front = 0 index = 1 while index < len(nums): node = node_queue[front] front += 1 item = nums[index] index += 1 if item is not None: node.left = TreeNode(item) node_queue.append(node.left) if index >= len(nums): break item = nums[index] index += 1 if item is not None: node.right = TreeNode(item) node_queue.append(node.right) return root # 循環方式支持 None節點建立 # 好比[5,1,4,None,None,3,2,None,10] # 展現的樹形以下: 5 1 4 3 2 10 即None表明那個index下的子節點爲空
測試app
nums = ['A','B','C','D','E','F'] root = createTree(nums, 0)
前序遍歷的規則:測試
(1)訪問根節點
(2)遍歷左子樹
(3)遍歷右子樹spa
def traversal(node): if node: print node.val if node.left: traversal(node.left) if node.right: traversal(node.right)
輸出:code
A
B
D
E
C
F遞歸
中序遍歷的規則:it
(1)遍歷左子樹
(2)訪問根節點
(3)遍歷右子樹class
def traversal(node): if node.left: traversal(node.left) if node: print node.val if node.right: traversal(node.right)
輸出:基礎
D
B
E
A
F
C
後序遍歷的規則:
(1)遍歷左子樹
(2)遍歷右子樹
(3)訪問根節點
def traversal(node): if node.left: traversal(node.left) if node.right: traversal(node.right) if node: print node.val
輸出:
D
E
B
F
C
A
注意:前序中序後序只是調整了打印val的順序