給定一個二叉樹的完整的層次遍歷序列(包含所有節點,包括空節點),利用這個序列生成一顆二叉樹。
我們首先來看怎樣對一顆二叉樹進行層序遍歷,下圖所示的二叉樹層次遍歷的結果為[a,b,c,d,e],在這個過程中,我們首先保存根節點a,然后遍歷a的左右節點b,d並保存下來,然后遍歷b的左右子節點並保存,然后遍歷d的子節點並保存,直到完成了整棵樹的遍歷。所以這個過程是一個保存節點然后取出遍歷的過程,它符合先進先出的順序,所以才用隊列來實現
首先定義二叉樹的類:
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None
層序遍歷:
1 def PrintFromTopToBottom(root): 2 ans=[] 3 if root==None: 4 return ans 5 else: 6 q=[root] 7 while q: 8 node=q.pop(0) 9 ans.append(node.val) 10 if node.left: 11 q.append(node.left) 12 if node.right: 13 q.append(node.right) 14 return ans
利用層序生成二叉樹則是一個相反的過程,對於序列[a,b,c,d,None,None,e]來說,b c是a的子節點,d None是b的子節點,None e是c的子節點。如果序列為l,那么l[0]是根節點,l[1]和l[2]是l[0]左右子結點,l[3]和l[4]是l[1]左右子節點......,所以每次取出兩個節點,依次作為之前節點的子節點。代碼如下:
1 def createtree(l): 2 if l[0]: 3 root=TreeNode(l[0]) 4 nodes=[root] 5 id=1
6 while nodes and id<len(l): 7 node=nodes[0]#依次為每個節點分配子節點 8 node.left=TreeNode(l[id]) if l[id] else None 9 nodes.append(node.left) 10 node.right=TreeNode(l[id+1]) if id<len(l)-1 and l[id+1] else None 11 nodes.append(node.right) 12 id+=2#每次取出兩個節點
13 nodes.pop(0) 14 return root 15 else: 16 return None
python版本:3.6