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.
class Solution {
public:
vector<vector<int> > levelOrder(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
queue<TreeNode *> level;
vector<vector<int> > container;
TreeNode *iroot;
vector<int> inner;
if(root==NULL)
return container;
level.push(root);
level.push(NULL);
inner.push_back(root->val);
container.push_back(inner);
inner.clear();
while(!level.empty()){
iroot=level.front();
level.pop();
if(iroot==NULL){
if(inner.size()==0)
break;
container.push_back(inner);
inner.clear();
level.push(NULL);
}
else{
if(iroot->left){
inner.push_back(iroot->left->val);
level.push(iroot->left);
}
if(iroot->right){
inner.push_back(iroot->right->val);
level.push(iroot->right);
}
}
}
return container;
}
};