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]
]
Solution:
/**
* 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> > r = vector<vector<int> >();
if(NULL == root) return r;
deque<TreeNode*> d = deque<TreeNode*>();
d.push_back(root);
while(!d.empty()){
int s = d.size();
vector<int> v = vector<int>();
v.reserve(s);
for(int i=0;i<s;i++){
TreeNode* p = d.front();
d.pop_front();
v.push_back(p->val);
if(NULL != p->left) d.push_back(p->left);
if(NULL != p->right) d.push_back(p->right);
}
r.push_back(v);
}
return r;
}
};
网友评论