''' 題目描述 請實現一個函數按照之字形打印二叉樹, 即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。 層序遍歷的變種,噹噹前層是奇數層的時候,將出棧結果保存 噹噹前層是偶數層時,將出棧結果序列逆序保存 ''' # -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def Print(self, pRoot): # write code here if not pRoot.left and not pRoot.right: return pRoot.val stack1=[] stack1.append(pRoot) output=[] is_ou=False while(len(stack1)>0): print(type(stack1[0]),type(stack1)) temp=[] temp_len=len(stack1) # print(temp_len) for i in range(temp_len): out_node=stack1.pop(0) # print(out_node.left,'hsihidsd') if out_node.left is not None: stack1.append(out_node.left) if out_node.right is not None: stack1.append(out_node.right) temp.append(out_node.val) # print(stack1) if not is_ou: output.extend(temp) else: output.extend(temp[::-1]) is_ou=~is_ou return output if __name__=='__main__': here=TreeNode(8) here.left=TreeNode(6) here.right=TreeNode(10) here.left.left=TreeNode(5) here.left.right = TreeNode(7) here.right.left = TreeNode(9) here.right.right = TreeNode(11) print(Solution().Print(here)) # [8, 10, 6, 5, 7, 9, 11]
python 按之字形順序打印二叉樹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.