[Sword refers to Offer] Zigzag printing binary tree [Python]

[Title requirements]: Please implement a function to print a binary tree in a zigzag pattern, that is, the first line is printed from left to right, the second layer is printed from right to left, and the third line is printed from left to right. print, and so on for other lines.

[Problem-solving ideas]: zigzag printing --> traverse the subtree of the node that comes in first --> similar to the idea of ​​a stack

Set up a stack to install the nodes of one layer (the source node, traverse its left and right subtrees according to the nodes of this stack, and it will become an empty stack after traversing this layer), but the left and right subtrees traversed also need Enter the stack, so it is necessary to set up an intermediate conversion stack (after traversing this layer, the source node for the next traversal is installed, and the recursive function is sent back)

For zigzag printing, you need to consider whether to traverse the left node or the right node first, so you need to consider the direction, then set a flag~

【First time code】:

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 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325169136&siteId=291194637