Title Description
Sword finger offer 32 prints a binary tree from top to bottom
- Each node of the binary tree is printed from top to bottom, and the nodes of the same layer are printed from left to right.
- The binary tree is printed by layers from top to bottom, the nodes of the same layer are printed from left to right, and each layer is printed to one line.
- Please implement a function to print the binary tree in zigzag order, that is, the first line is printed from left to right, the second layer is printed from right to left, the third line is printed from left to right, and so on.
For example:
Given binary tree: [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
1. The results of 2 and 3 are as follows:
1. [3,9,20,15,7] 2. [ [3], [9,20], [15,7] ] 3. [ [3], [20,9], [15,7] ]
First question
Problem solving ideas
Print the binary tree by layer, that is, the breadth first search (BFS) of the binary tree. Generally, we can use the first in first out feature of the queue to traverse the sequence. Each time, a node pops up from the head of the queue, and judge whether the node has left and right child nodes. If so, add it to the tail of the queue, and then add this node to the result queue, The above operations can be performed in the loop. When the queue is empty, exit the loop.
Here, python is used to solve the problem. You can use the double ended queue deque in collections. The time complexity of the function popup () from the head of the queue is O(1)
Complexity
Time complexity: O(n), traversing n nodes
Space complexity: O(n), which uses the additional space of double ended queue n
supplement
Initialization of double ended queue: queue = collections.dequeue(, [[]). The parentheses are optional parameters. The default is an empty list. The parameter can be a list, that is, convert the list into a double ended queue.
Some methods:
queue.pop()
queue.popleft()
queue.append(value)
queue.appendleft(value)
code implementation
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[int]: if not root: return [] res , queue = [] , collections.deque([root]) while queue: node = queue.popleft() res.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return res
Second question
Problem solving ideas
The second question requires that the nodes of the same layer should be printed on one line, so we can add an additional list tmp to store the node values of the same layer.
Algorithm flow
- Special case handling: if the tree is empty, an empty list is returned
- Initialization: a list res is used to store the final result, and the dual end queue initialization is stored in the root node root
- BFS cycle: exit when queue is empty:
- Create a new tmp empty list to store node values of the same layer
- The cycle is printed by layer, and the number of cycles is the number of nodes in the current layer, that is, the length of the queue:
- Out of queue: the first node in the queue is assigned to node
- Add to tmp: add node.val to the list
- Enqueue: enqueue if there are child nodes
- Add the result tmp of the current layer to res
- Return result res
Complexity
Time complexity: O(n), traversing n nodes
Space complexity: O(n). In the worst case, when the tree is a balanced binary tree, there are at most N/2 nodes in the queue, using the additional space of O(n).
code implementation
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res , queue = [] , collections.deque([root]) while queue: tmp = [] for _ in range(len(queue)): #The number of cycles is the number of nodes in the current layer node = queue.popleft() tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) res.append(tmp) return res
Third question
Problem solving ideas
The third question adds a requirement on the basis of the second question: that is, if you print in zigzag, you can see that odd layers are printed from left to right and even layers are printed from right to left. Therefore, you can judge the odd and even layers through an identifier and perform the corresponding operations:
The even layer leaves the team from the end of the team, and the left and right child nodes enter the team from the head of the team, so as to achieve the effect of reverse printing.
The odd layer leaves the team from the first of the team, and the * * left and right * * child nodes join the team from the end of the team;
However, in this way, the order of odd sub layers is opposite to that expected, so we can exchange the queue order of left and right sub nodes, that is, the right node enters the queue first and the left node enters the queue later.
Complexity
Time complexity: O (n), BFS cycles n times, n is the number of nodes.
Spatial complexity: O(n), the same as the second question.
code implementation
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: if not root: return [] res , queue = [] , collections.deque([root]) flag = True #Parity identification while queue: tmp = [] for _ in range(len(queue)): if flag: node = queue.popleft() tmp.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) else: node = queue.pop() tmp.append(node.val) if node.right: queue.appendleft(node.right) if node.left: queue.appendleft(node.left) res.append(tmp) flag = not flag return res
Welcome to my blog: [Victor's blog]( http://www.victorcoding.top )