【劍指offer】之字形列印二叉樹【python】
阿新 • • 發佈:2018-11-26
題目描述
請實現一個函式按照之字形列印二叉樹,即第一行按照從左到右的順序列印,第二層按照從右至左的順序列印,第三行按照從左到右的順序列印,其他行以此類推。
在上一篇部落格中:層次遍歷,每一層在一行輸出中,只需要將奇數行的result反轉一下就行了
另外一種方法就是,需要反轉佇列的結果,想到就是用到棧
需要用到兩個棧,依次入棧,出棧,輸出就行
如果列印是奇數層,先儲存左節點再儲存右節點到棧,如果是偶數,則先儲存右再儲存左
class TreeNode:
def __init__(self, x):
self.val = x
self. left = None
self.right = None
class Solution:
def Print(self, pRoot):
# write code here
list = [] #佇列
result = [] #每一層的結果
results = [] #儲存result的list
nextLevel = 0
toBeList = 1 #這層還需要加入result的元素個數
if pRoot == None:
return list
list.append(pRoot)
while list != []:
treeNode = list.pop(0)
toBeList -= 1
result.append(treeNode.val)
if treeNode.left:
nextLevel += 1
list.append(treeNode.left)
if treeNode.right:
nextLevel += 1
list.append(treeNode.right)
if toBeList == 0:
results.append(result)
result = []
toBeList = nextLevel
nextLevel = 0
for i, result in enumerate(results):
if i & 0x1 == 1:
result.reverse()
return results
結果
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.right.left = TreeNode(5)
root.right.right = TreeNode(6)
results = Solution().Print(root)
for i in results:
print(i)
>>>
[1]
[3, 2]
[4, 5, 6]