leetcode589. N-ary Tree Preorder Traversal

Posted 业精于勤荒于嬉,行成于思毁于随

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode589. N-ary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。

题目:

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].

 

Note:

Recursive solution is trivial, could you do it iteratively?

 
1. Recursive solution:
 
/*
// 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) {
        vector<int> order = {};
        if (root) {
            traversal(root, order);
        }
        
        return order;
    }
    
    void traversal(Node* root, vector<int> &order) {
        order.push_back(root->val);
        int num = root->children.size();
        for (int i = 0; i < num; i++) {
            traversal(root->children.at(i), order);
        }
    }
};

  

2. Iterative  solution:

/*
// 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) {
        vector<int> order = {};
        stack<Node*> nodeStack;
        if (root) {
            nodeStack.push(root);
        }
        
        while (!nodeStack.empty()) {
            Node* node = nodeStack.top();
            nodeStack.pop();
            order.push_back(node->val);
            int num = node->children.size();
            for (int i = num - 1; i >= 0; i--) {
                nodeStack.push(node->children.at(i));
            }
        }
        
        return order;
    }
    
};

  

以上是关于leetcode589. N-ary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode&Python] Problem 589. N-ary Tree Preorder Traversal

leetcode589. N-ary Tree Preorder Traversal

[LeetCode] 589. N-ary Tree Preorder Traversal_Easy

LeetCode 589. N叉树的前序遍历(N-ary Tree Preorder Traversal)

LeetCode 589 N-ary Tree Preorder Traversal 解题报告

[LeetCode] 589. N-ary Tree Preorder Traversal