給定一個二叉樹,傳回其按層次周遊的節點值。 (即逐層地,從左到右通路所有節點)。
例如:
給定二叉樹: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
傳回其層次周遊結果:
[
[3],
[9,20],
[15,7]
]
層序周遊指按層次的順序從根結點向下逐層進行周遊,且對同一層的節點為從左到右周遊。
基本思路:從根結點開始廣度優先搜尋
- 将根結點root加入隊列
- 取出隊首結點,通路它
- 如果該結點有左孩子,将左孩子入隊。
- 如果該結點有右孩子,将右孩子入隊
- 傳回第二步,直到隊列為空
/**
* 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>> res;
if(root == NULL) {
return res;
}
queue<TreeNode*> q;
TreeNode* p;
q.push(root);
while(!q.empty()) {
vector<int> temp;
int width = q.size();
for(int i = 0; i < width; i++) {
p = q.front();
temp.push_back(p->val);
q.pop();
if(p->left) {
q.push(p->left);
}
if(p->right) {
q.push(p->right);
}
}
res.push_back(temp);
}
return res;
}
};
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int>> res;
q.push(root);
if(root==NULL){
return res;
}
while(!q.empty()){
queue<TreeNode*> qt;
vector<int> v;
while(!q.empty()){
TreeNode* now = q.front();
q.pop();
v.push_back(now->val);
if(now->left!=NULL){
qt.push(now->left);
}
if(now->right!=NULL){
qt.push(now->right);
}
}
res.push_back(v);
q = qt;
}
return res;
}
};