您的位置:首页 > 职场人生

Leetcode Binary Tree Level Order Traversal II

2013-10-26 21:13 253 查看
与上一题类似,不过要求按倒序来输出。存的时候用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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 OJ leetcode