与上一题类似,不过要求按倒序来输出。存的时候用stack来存就可以了。遍历完后再存到vector里面。
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<int> > ans;
if(root == NULL) return ans;
vector<int> v;
queue<TreeNode*> node;
queue<int> index;
stack<vector<int> > s;
node.push(root);
index.push(1);
int tag = 1;
TreeNode *n;
int i;
while(!node.empty()){
n = node.front();
i = index.front();
node.pop();
index.pop();
if(n->left != NULL){
node.push(n->left);
index.push(i+1);
}
if(n->right != NULL){
node.push(n->right);
index.push(i+1);
}
if(tag != i){
tag = i;
s.push(v);
v.clear();
}
v.push_back(n->val);
}
s.push(v);
while(!s.empty()){
ans.push_back(s.top());
s.pop();
}
return ans;
}
};