您的位置:首页 > 其它

102. Binary Tree Level Order Traversal

2017-01-10 21:39 225 查看
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,null,null,15,7],

3
/ \
9  20
/  \
15   7


return its level order traversal as:

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


bfs思路

/**
* 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<TreeNode*> father, son;
father.push_back(root);
vector<vector<int>> ans;
if(root == NULL) return ans;
else ans.push_back({root->val});
vector<int> tmp;
int cnt = 0;
while(1){
if(root->left != NULL){
son.push_back(root->left);
tmp.push_back(root->left->val);
}
if(root->right != NULL){
son.push_back(root->right);
tmp.push_back(root->right->val);
}
++cnt;
if(cnt == father.size()){
father = son;
cnt = 0;
if(father.empty())
break;
ans.push_back(tmp);
son.clear();
tmp.clear();
}
root = father[cnt];
}
return ans;
}
};


/**
* 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;
deque<TreeNode*> bfs;
int cntPar = 0, cntSon = 0;
if(root == NULL) return res;
else
{
bfs.push_back(root);
cntPar = 1;
}
int tmp = 0;
vector<int> vec;
while(1){
if(root->left != NULL){
bfs.push_back(root->left);
cntSon++;
}
if(root->right != NULL){
bfs.push_back(root->right);
cntSon++;
}

tmp++;
vec.push_back(root->val);

if(tmp == cntPar){
res.push_back(vec);
vec.clear();
cntPar = cntSon;
tmp = 0;
cntSon = 0;
}
bfs.pop_front();
if(bfs.empty())
break;
root = bfs.front();

}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: