leetcode 589. N 叉树的前序遍历

81 阅读1分钟

c++

class Solution {
public:
    vector<int> ans;
    vector<int> preorder(Node* root) {
        if (!root) return ans;   
        ans.push_back(root->val);
        for (int i = 0; i < root->children.size(); i++) { 
            preorder(root->children[i]);
        }
        return ans;
    }
};

js

var preorderImpl = function(root, ans) {
    if (!root) return ;
    ans.push(root.val);
    for (var node of root.children) {
        preorderImpl(node, ans);
    }
    return ;
}

var preorder = function(root) {
    let ans = [];
    if (!root) return ans;
    preorderImpl(root, ans);
    return ans;
};