leetcode 剑指 Offer 32 - II. 从上到下打印二叉树 II

115 阅读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>> levelOrder(TreeNode* root) {
        if (!root) return vector<vector<int>> ();
        vector<vector<int>> ans;
        levelOrderImpl(root, ans, 0);
        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 levelOrder = function(root) {
    var ans = [];
    if (!root) return ans;
    levelOrderImpl(root, ans, 0);
    return ans;
};