Binary Tree Level Order Traversal II
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree
return its bottom-up level order traversal as:
*/For example:
Given binary tree
{3,9,20,#,#,15,7}, 3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[ [15,7] [9,20], [3], ]
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > levelOrderBottom(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int impossibleVal = 20000;
vector<vector<int>> result;
if(root==NULL) return result;
TreeNode *divider = new TreeNode(impossibleVal);
vector<int> line;
TreeNode *curr;
queue<TreeNode*> q;
q.push(root);
q.push(divider);
while(!q.empty()){
curr = q.front();
q.pop();
if(curr->val==impossibleVal){
if(line.size()!=0) result.insert(result.begin(), line);
line.clear();
if((!q.empty()) && q.front()->val!=impossibleVal){
divider = new TreeNode(impossibleVal);
q.push(divider);
}
}
else {
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
line.push_back(curr->val);
}
}
return result;
}
};
No comments:
Post a Comment