题目描述:

方法1:递归

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

方法2:非递归,使用栈

class Solution {
public:
    vector<int> preorder(Node* root) {
        vector<int> result;
        stack<Node*> stk;
        if(!root) return result;
        stk.push(root);

        while(!stk.empty()){
            Node* temp = stk.top();
            stk.pop();
            result.push_back(temp->val);
            for(int i=(temp->children).size()-1;i>-1;i--){
                stk.push((temp->children)[i]);
            }
        }
        return result;
    }
};