102 Binary Tree Level Order Traversal
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>> res;
if ( root == NULL ) return res;
vector<TreeNode*> res1(1, root);
while ( res1.size() != 0 ) {
int nres = res1.size();
vector<int> tmp;
vector<TreeNode*> res2;
for ( int i = 0; i <= nres-1; i++ ) {
tmp.push_back(res1[i]->val);
if ( res1[i]->left != NULL ) res2.push_back(res1[i]->left);
if ( res1[i]->right != NULL ) res2.push_back(res1[i]->right);
}
res.push_back(tmp);
res1 = res2;
}
return res;
}
};