Binary tree level traversal binary-tree-level-order-traversal
Title description
Given a binary tree, return the result of the traversal of the binary tree sequence, (traversing layer by layer from left to right)
For example:
the given binary tree is {3,9,20,#,#,15,7},
3↵ / ↵ 9 20↵ / ↵ 15 7
The result of this binary tree sequence traversal is
[↵ [3],↵ [ 9,20],↵ [15,7]↵]
If you don’t know the meaning of "{1,#,2,3}", please continue reading.
We use the following method to serialize the
binary tree : the serialization of the binary tree follows the principle of layer order traversal, "#" means that the position is a line At the end of the path, there are no more nodes below.
For example:
1↵ / ↵ 2 3↵ /↵ 4↵ ↵ 5
The result of the above binary tree serialization is: "{1,2,3,#,#,4,#,#,5}".
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example:
Given binary tree{3,9,20,#,#,15,7},
3↵ / ↵ 9 20↵ / ↵ 15 7↵
return its level order traversal as:
[↵ [3],↵ [9,20],↵ [15,7]↵]↵
confused what"{1,#,2,3}"means?
Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.
Here’s an example:
1↵ / ↵ 2 3↵ /↵ 4↵ ↵ 5↵
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
Example
Example 1
input
{1,2}
Output
[[1],[2]]
Example 2
input
{1,2,3,4,#,#,5}
Output
[[1],[2,3],[4,5]]
Problem-solving ideas
- The level traversal of the binary tree is solved by a queue. Pay attention to the number of nodes at each level
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode* root) {
vector<vector<int> > res;
if(root == NULL) return res;
queue<TreeNode*> myque;
myque.push(root);
//只要队列不空
while(!myque.empty()) {
vector<int> cur; //保存当前层的所有节点值
int size = myque.size(); //每次先保存当前层的节点数
//当前层的所有节点全部依次出队并加入cur,然后把下一层的节点全部放进来,等待下一次大循环
for(int i = 0; i < size; i ++) {
TreeNode* p = myque.front();
myque.pop();
cur.push_back(p -> val);
if(p -> left) myque.push(p -> left);
if(p -> right) myque.push(p -> right);
}
res.push_back(cur);
}
return res;
}
};