leetcode 107. 二叉树的层序遍历 II

72 阅读1分钟

c++

class Solution {
public:
    void levelOrderImpl(TreeNode *root, vector<vector<int> > &ans, int deepth) {
        if (!root) return ;
        if (ans.size() == deepth) ans.push_back(vector<int> ());
        ans[deepth].push_back(root->val);
        levelOrderImpl(root->left, ans, deepth + 1);
        levelOrderImpl(root->right, ans, deepth + 1);
        return ;
    }

    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if (!root) return vector<vector<int>> ();
        vector<vector<int>> ans;
        levelOrderImpl(root, ans, 0);
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

js

function levelOrderImpl(root, ans, deepth) {
    if (!root) return ;
    if (ans.length == deepth) ans.push([]);
    ans[deepth].push(root.val);
    levelOrderImpl(root.left, ans, deepth + 1);
    levelOrderImpl(root.right, ans, deepth + 1);
    return ;
}

var levelOrderBottom = function(root) {
    let ans = [];
    if (!root) return ans;
    levelOrderImpl(root, ans, 0);
    ans.reverse();
    return ans;
};