Binary Tree Level Order Traversal II leetcod c++

来源:互联网 发布:dnf台服内部辅助源码 编辑:程序博客网 时间:2024/06/03 12:34
与之前的

Binary Tree Level Order Traversal 

基本没有什么大的区别,既然要求输出倒叙的,那我们先找个stack储存结果就是了。代码见下面。

/** * 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>> ans;    stack<vector<int>> temp;    if(root == NULL)        return ans;    int count = 1;    queue<TreeNode *> q;    q.push(root);    vector<int> cur(0);    while(!q.empty())    {           cur.clear();        int tmp = 0;        for(int i = 0;i<count;i++)        {            root = q.front();            cur.push_back(root->val);            q.pop();            if(root->left!=NULL)            {                q.push(root->left);                tmp++;            }            if(root->right!=NULL)            {                q.push(root->right);                tmp++;            }        }        count = tmp;        temp.push(cur);    }    // int hello = temp.size();       at first, I did not this line so i< temp.size();    // for(int i = 0;i< hello;i++)    i and the temp.size() are all changed.it can not present the number in stack    // {    while(!temp.empty())    {        ans.push_back(temp.top());        temp.pop();    }    return ans;            }};

0 0
原创粉丝点击