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

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

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

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

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

【第一次代码】:

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 

猜你喜欢

转载自blog.csdn.net/Jillian_sea/article/details/80172290
今日推荐