LeetCode 107. Binary Tree Level Order Traversal II

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

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;
    }
};

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值