107. 二叉树的层序遍历 II

107. 二叉树的层序遍历 II


题目链接:107. 二叉树的层序遍历 II

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        stack<vector<int>> result_temp;

        queue<TreeNode*> que;
        if(root!=nullptr)
            que.push(root);

        //先用栈的先进后出特性存储每层元素,就变成逆序了,在存回到vector中
        while(!que.empty())
        {
            vector<int> temp;
            int len=que.size();
            
            for(int i=0;i<len;i++)
            {
                TreeNode *p=que.front();
                que.pop();
                temp.push_back(p->val);
                if(p->left)
                    que.push(p->left);
                if(p->right)
                    que.push(p->right);
            }
            result_temp.push(temp);
        }

        while(!result_temp.empty())
        {
            result.push_back(result_temp.top());
            result_temp.pop();
        }

        return result;

    }
};

你可能感兴趣的:(leetcode,c++)