102. Binary Tree Level Order Traversal My Submissions Question
Total Accepted: 96217 Total Submissions: 297797 Difficulty: Easy
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? > read more on how binary tree is serialized on OJ.
OJ's 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
Total Accepted: 96217 Total Submissions: 297797 Difficulty: Easy
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? > read more on how binary tree is serialized on OJ.
OJ's 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}".
解题思路:两个队列
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> Ans;//存放最后结果
if(root==NULL)return Ans;//根节点为空
queue<TreeNode*> Q;
Q.push(root);//根节点进队列
while(!Q.empty()){
vector<int> temp;//存放当前层的值
queue<TreeNode*> tempQ;//存放下一层的结点队列(缓存)
while(!Q.empty()){
TreeNode *head=Q.front();//取队首元素
temp.push_back(head->val);
Q.pop();
if(head->left!=NULL)tempQ.push(head->left);//左孩子非空,进入下一层的结点队列(缓存)
if(head->right!=NULL)tempQ.push(head->right);//右孩子非空,进入下一层的结点队列(缓存)
}
Q=tempQ;//遍历下一层
Ans.push_back(temp);//保存一层结点的值
}
return Ans;
}
};