LeetCode 107. Binary Tree Level Order Traversal II

来源:互联网 发布:网络劫持 编辑:程序博客网 时间:2024/06/11 01:05

层序遍历二叉树
遍历时队列中存储的是指针,方便出队时找到其左右节点。

class Solution {public:    vector<vector<int>> levelOrderBottom(TreeNode* root) {        vector<vector<int>> result;        if(!root)return result;        stack<vector<int>> tempResult;        vector<TreeNode*> vec;//模拟队列        vector<TreeNode*> temp;//保存层序遍历一层的节点        vec.push_back(root);        int i=0;//队列的起点        int tail=0;        while(i<vec.size()){            temp.push_back(vec[i]);            if(vec[i]){                vec.push_back(vec[i]->left);                vec.push_back(vec[i]->right);            }            if(i==tail){                vector<int> tempVec;                for(int j=0;j<temp.size();j++)                    if(temp[j])tempVec.push_back(temp[j]->val);                if(tempVec.size()>0)//因为temp中的元素是指针,所以当temp中都为NULL时,tempVec为空                    tempResult.push(tempVec);                temp.clear();                tail=vec.size()-1;            }            i++;        }        while(!tempResult.empty()){            result.push_back(tempResult.top());            tempResult.pop();        }        return result;    }};

考虑如何在队列中直接存储整型数据,而不是节点的指针???

0 0
原创粉丝点击