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
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]Solution:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
queue<TreeNode*> H; | |
H.push(root); | |
int cur=1; | |
int next=0; | |
vector<int> C; | |
while(!H.empty()){ | |
TreeNode* front=H.front(); | |
H.pop(); | |
if(front!=NULL){ | |
C.push_back(front->val); | |
H.push(front->left); | |
H.push(front->right); | |
next+=2; | |
} | |
cur--; | |
if(cur==0&&!C.empty()){ | |
res.push_back(C); | |
C.clear(); | |
cur=next; | |
next=0; | |
} | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment