N-叉树的前序遍历(两种方法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35747066/article/details/89453601

589. N-ary Tree Preorder Traversal

Easy

19930FavoriteShare

Given an n-ary tree, return the preorder traversal of its nodes' values.

For example, given a 3-ary tree:

Return its preorder traversal as: [1,3,5,6,2,4].

递归方法:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> preorder(Node* root) {
        if(root == NULL){
            return Result;
        }
        Result.push_back(root->val);
        for(auto child : root->children){
            preorder(child);
        }
        return Result;
    }
    private:
        vector<int> Result;
};

非递归方法(能减少很多时间)

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector<int> preorder(Node* root) {
        if(root == NULL){return Result;}
        s.push(root);
        while(!s.empty()){
            Node* tmp = s.top();
            Result.push_back(tmp->val);
            s.pop();
            vector<Node*>::reverse_iterator it = tmp->children.rbegin();
            for(it;it != tmp->children.rend();it++){
                s.push(*it);
            }
        }
        return Result;
    }
    private:
        vector<int> Result;
        stack<Node*> s;
};

猜你喜欢

转载自blog.csdn.net/qq_35747066/article/details/89453601
今日推荐