二叉树的层序遍历Ⅱ-力扣

作者 : admin 本文共729个字,预计阅读时间需要2分钟 发布时间: 2024-06-5 共2人阅读

很简单的一道题,将前一道题的结果数组进行一次反转即可。

/**
 * 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:
    void order(TreeNode* cur, vector<vector<int>>& result, int depth){
        if(cur == nullptr){
            return;
        }
        if(result.size() == depth){
            result.push_back(vector<int>());
        }
        result[depth].push_back(cur->val);
        order(cur->left, result, depth + 1);
        order(cur->right, result, depth + 1);
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        int depth = 0;
        order(root, result, depth);
        reverse(result.begin(), result.end());
        return result;
    }
};
本站无任何商业行为
个人在线分享 » 二叉树的层序遍历Ⅱ-力扣
E-->