Sword refers to offer-32_2. Print the binary tree into multiple lines-analysis and code [Java]
1. Title
The binary tree is printed layer by layer from top to bottom, and the nodes of the same layer are output from left to right. Output one line per layer.
Two, analysis and code
1. Queue
(1) Thinking
Design an auxiliary queue, pop the head node in turn, and pop its child nodes into the tail of the queue.
To achieve layering, an integer can be used to record the number of nodes in each layer. After all nodes in each layer are visited, the size of the queue is the number of nodes in the next layer.
(2) Code
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
if (pRoot == null)
return ans;
Queue<TreeNode> que = new LinkedList<TreeNode>();
que.offer(pRoot);
int num = 1;
while(!que.isEmpty()) {
ArrayList<Integer> vals = new ArrayList<>();
int nextNum = 0;
for (int i = 0; i < num; i++) {
TreeNode node = que.peek();
que.poll();
vals.add(node.val);
if (node.left != null) {
que.offer(node.left);
nextNum++;
}
if (node.right != null) {
que.offer(node.right);
nextNum++;
}
}
num = nextNum;
ans.add(vals);
}
return ans;
}
}
(3) Results
Running time: 15 ms, occupying 9744 k of memory.
Three, other
Nothing.