Problem:
Solution:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// Use reverse(sol.begin(), sol.end()) instead of following.
/*
void reverse(vector<vector<int> > &sol) {
int size = sol.size();
int start = 0;
int end = size - 1;
while (start < end) {
vector<int> temp;
temp = sol[start];
sol[start] = sol[end];
sol[end] = temp;
start++;
end--;
}
}
*/
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > sol;
if (root == NULL)
return sol;
vector<TreeNode *> prev, curr;
prev.push_back(root);
while (prev.size() != 0) {
int size = prev.size();
vector<int> curr_int;
for (int i = 0; i < size; i++) {
curr_int.push_back(prev[i] -> val);
if (prev[i] -> left)
curr.push_back(prev[i] -> left);
if (prev[i] -> right)
curr.push_back(prev[i] -> right);
}
prev = curr;
curr.clear();
sol.push_back(curr_int);
}
reverse(sol.begin(), sol.end());
return sol;
}
};
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
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] ]
Solution:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// Use reverse(sol.begin(), sol.end()) instead of following.
/*
void reverse(vector<vector<int> > &sol) {
int size = sol.size();
int start = 0;
int end = size - 1;
while (start < end) {
vector<int> temp;
temp = sol[start];
sol[start] = sol[end];
sol[end] = temp;
start++;
end--;
}
}
*/
vector<vector<int> > levelOrderBottom(TreeNode *root) {
vector<vector<int> > sol;
if (root == NULL)
return sol;
vector<TreeNode *> prev, curr;
prev.push_back(root);
while (prev.size() != 0) {
int size = prev.size();
vector<int> curr_int;
for (int i = 0; i < size; i++) {
curr_int.push_back(prev[i] -> val);
if (prev[i] -> left)
curr.push_back(prev[i] -> left);
if (prev[i] -> right)
curr.push_back(prev[i] -> right);
}
prev = curr;
curr.clear();
sol.push_back(curr_int);
}
reverse(sol.begin(), sol.end());
return sol;
}
};
No comments:
Post a Comment