Sunday, March 6, 2016

LeetCode Q102: 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,#,#,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;
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;
}
};
view raw Q102.cpp hosted with ❤ by GitHub

No comments:

Post a Comment