# Title Description

To give you a binary tree, please return the node values obtained by traversing in sequence. (that is, access all nodes from left to right layer by layer).

Example: Binary tree: [3,9,20,null,null,15,7],

3 / \ 9 20 / \ 15 7 Return its sequence traversal result:

[ , [9,20], [15,7] ]

## Problem solving ideas

DFS (depth first search) and BFS (breadth first search) are like twin brothers. When you mention one, you always think of another. However, in practice, we use DFS much more than BFS. So, is BFS useless?

If we only use DFS/BFS to traverse all nodes in a tree and a graph, there is no difference in the capabilities of DFS and BFS. Of course, we prefer DFS traversal with more write convenience and lower space complexity. However, DFS can only use BFS traversal for some usage scenarios, such as "sequence traversal" in this topic.

Let's first look at the code comparison between DFS traversal and BFS traversal on a binary tree.

DFS traversal uses recursion:

```void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
dfs(root.right);
}```

BFS traversal uses queue data structure:

```void bfs(TreeNode root) {
Queue<TreeNode> queue = new ArrayDeque<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // Java pop writing (poll)
if (node.left != null) {
}
if (node.right != null) {
}
}
}```

Just comparing the two pieces of code, the most intuitive feeling is that the DFS traversal code is too concise than BFS! This is because the recursive method implicitly uses the system stack, and we don't need to maintain a data structure ourselves. If you simply traverse the binary tree, DFS is obviously a more convenient choice.

Although DFS and BFS traverse all nodes of the binary tree, they traverse nodes in different order.

This traversal order is also the fundamental reason why BFS can be used to solve the "sequence traversal" problem.

What is sequence traversal? In short, sequence traversal is to layer the binary tree, and then traverse each layer from left to right: At first glance, this traversal order is the same as BFS. We can directly use BFS to obtain the sequence traversal result. However, the input results required for sequence traversal and BFS are different. Sequence traversal requires us to distinguish each layer, that is, to return a two-dimensional array. The traversal result of BFS is a one-dimensional array, which can not distinguish each layer. So, how to layer the results of BFS traversal? Let's first observe the process of nodes entering and leaving the queue during BFS traversal: Intercept a time during BFS traversal: You can see that the nodes in the queue are 3, 4 and 5, which are from layer 1 and layer 2 respectively. At this time, before the nodes of layer 1 are finished, the nodes of layer 2 come in, and the nodes of the two layers are close together in the queue. We can't distinguish which layer the nodes in the queue come from.

Therefore, we need to modify the code slightly. Before traversing each layer, first record the number of nodes in the queue n (that is, the number of nodes in this layer), and then process the N nodes in this layer at one go.

```// Sequence traversal of binary tree
void bfs(TreeNode root) {
Queue<TreeNode> queue = new ArrayDeque<>();
while (!queue.isEmpty()) {
int n = queue.size();
for (int i = 0; i < n; i++) {
// Variable i has no practical meaning, just to cycle n times
TreeNode node = queue.poll();
if (node.left != null) {
}
if (node.right != null) {
}
}
}
}```

In this way, we transform BFS traversal into sequence traversal. In the process of traversal, the process of nodes entering and leaving the queue is as follows: It can be seen that in each round of the while loop, all nodes of the current layer are out of the queue, and then all nodes of the next layer are in the queue, so as to realize sequence traversal.

The final solution code is:

```public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();

Queue<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
}
while (!queue.isEmpty()) {
int n = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < n; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
}
if (node.right != null) {
}
}
{"ft_lang_label":"__label__en","ft_lang_prob":0.7878582,"math_prob":0.8818488,"size":4775,"snap":"2022-40-2023-06","text_gpt3_token_len":1089,"char_repetition_ratio":0.16600293,"word_repetition_ratio":0.10958904,"special_character_ratio":0.25570682,"punctuation_ratio":0.17023446,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99348974,"pos_list":[0,1,2,3,4,5,6,7,8,9,10],"im_url_duplicate_count":[null,1,null,1,null,1,null,1,null,1,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-09-29T04:30:33Z\",\"WARC-Record-ID\":\"<urn:uuid:69957b40-5b5a-43b6-bc50-b7f48d1038a5>\",\"Content-Length\":\"12059\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:e71e07d3-af67-4925-8a37-233c67cdb5d3>\",\"WARC-Concurrent-To\":\"<urn:uuid:71b77f70-abbb-469f-9f7d-15d20166808b>\",\"WARC-IP-Address\":\"154.12.245.167\",\"WARC-Target-URI\":\"https://programmer.help/blogs/sequence-traversal-of-leetcode-no.102-binary-tree.html\",\"WARC-Payload-Digest\":\"sha1:PWQUFGDED33TMXVVBPE4QQNVLXTAD3OK\",\"WARC-Block-Digest\":\"sha1:BVODYOVZWZJ4XXXNYPXGN6YE6MHRJUJ6\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030335304.71_warc_CC-MAIN-20220929034214-20220929064214-00029.warc.gz\"}"}