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]
]
/**
* 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) {
if(root == NULL){
vector<vector<int> >ans();
return ans;
} queue<pair<TreeNode*,int> >q;
q.push(make_pair(root,)); vector<vector<int> >ans; while(!q.empty()){
TreeNode* t=q.front().first;
int depth=q.front().second; if(ans.size()==depth){
ans.push_back(vector<int>());
} ans[depth].push_back(t->val); if(t->left!=NULL){
q.push(make_pair(t->left,depth+));
}
if(t->right!=NULL){
q.push(make_pair(t->right,depth+));
}
q.pop();
} return ans; }
};
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> >ans; void dfs(TreeNode* r,int depth){
if(r==NULL) return ; if(ans.size()==depth){
ans.push_back(vector<int>());
}
ans[depth].push_back(r->val); dfs(r->left,depth+);
dfs(r->right,depth+);
} vector<vector<int> > levelOrder(TreeNode* root) {
dfs(root,);
return ans;
} };
DFS法