【剑指Offer】之字形打印二叉树[Python]

xiaoxiao2021-02-28  39

【题目要求】:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

【解题思路】:之字形打印-->先遍历后进来的节点的子树-->类似于栈的思想

设置一个栈用来装上一层的节点(源节点,根据这一个栈的节点遍历它的左右子树,遍历完这一层之后会变成空栈),但遍历到的左右子树也需要进栈,所以有要设置一个中间转换栈(遍历完这一层之后装有下一次遍历的源节点,重新送回递归函数)

之字形打印,需要考虑先遍历左节点还是右节点,所以需要考虑方向,那就设置一个flag吧~

注意:提交一次代码后发现结果要求是list套list的,所以又设置了一个中间转换list,这样每次append的时候都可以保证元素也是list形式的

【第一次代码】:

class Solution:

    def Zprint(self, list_out,stack,direction):         if stack:             temp_stack = []             temp_list = []             direction = not direction             while stack:                 root = stack.pop()                 if direction:                     if root.left:                         temp_list.append(root.left.val)                         temp_stack.append(root.left)                     if root.right:                         temp_list.append(root.right.val)                         temp_stack.append(root.right)                 else:                     if root.right:                         temp_list.append(root.right.val)                         temp_stack.append(root.right)                     if root.left:                         temp_list.append(root.left.val)                         temp_stack.append(root.left)             if temp_list: list_out.append(temp_list)             self.Zprint(list_out, temp_stack, direction)                                       def Print(self, pRoot):         # write code here         list_out = []         stack = []         if pRoot:             list_out.append([pRoot.val])             stack.append(pRoot)             direction = True#右向左             self.Zprint(list_out,stack,direction)         return list_out 
转载请注明原文地址: https://www.6miu.com/read-2622043.html

最新回复(0)