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

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:

 

N-叉树的前序遍历(两种方法)_第1张图片

 

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

递归方法:

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

    Node() {}

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

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

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

    Node() {}

    Node(int _val, vector _children) {
        val = _val;
        children = _children;
    }
};
*/
class Solution {
public:
    vector 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::reverse_iterator it = tmp->children.rbegin();
            for(it;it != tmp->children.rend();it++){
                s.push(*it);
            }
        }
        return Result;
    }
    private:
        vector Result;
        stack s;
};

 

你可能感兴趣的:(N-叉树的前序遍历(两种方法))