''' 题目描述 请实现一个函数按照之字形打印二叉树, 即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。 层序遍历的变种,当当前层是奇数层的时候,将出栈结果保存 当当前层是偶数层时,将出栈结果序列逆序保存 ''' # -*- 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 按之字形顺序打印二叉树
最新推荐文章于 2020-08-02 11:05:58 发布