/**
* 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) {
vector<vector<int> > result;
if(root == NULL) {
return result;
}
vector<TreeNode *> output;
output.emplace_back(root);
levelOrderBottomHelper(output, result);
return result;
}
void levelOrderBottomHelper(vector<TreeNode *>& output, vector<vector<int> >& result) {
vector<TreeNode *> nodes;
for(int i = 0; i < output.size(); ++i) {
if(output[i]->left != NULL) {
nodes.emplace_back(output[i]->left);
}
if(output[i]->right != NULL) {
nodes.emplace_back(output[i]->right);
}
}
if(!nodes.empty()) {
levelOrderBottomHelper(nodes, result);
}
vector<int> temp;
for(TreeNode * node : output) {
temp.emplace_back(node->val);
}
result.emplace_back(temp);
}
};
4/20/2014
Leetcode -- Binary Tree Level Order Traversal II
Here we use recursion as stack
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment