1. 程式人生 > >Leetcode589.N-ary Tree Preorder TraversalN叉樹的前序遍歷

Leetcode589.N-ary Tree Preorder TraversalN叉樹的前序遍歷

給定一個 N 叉樹,返回其節點值的前序遍歷。

 

 

class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};

//遞迴
class Solution {
public:
    vector<int> res;
    vector<int> preorder(Node* root) {
        if(root == NULL)
            return res;
        GetAns(root);
        return res;
    }

    void GetAns(Node* root)
    {
        if(root == NULL)
            return;
        res.push_back(root ->val);
        int len = root ->children.size();
        for(int i = 0; i < len; i++)
        {
            GetAns(root ->children[i]);
        }
    }
};