Skip to content

Latest commit

 

History

History
67 lines (47 loc) · 1.51 KB

589-n-ary-tree-preorder-traversal.md

File metadata and controls

67 lines (47 loc) · 1.51 KB

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

给定一个 N 叉树,返回其节点值的前序遍历

例如,给定一个 3叉树 :

 

 

返回其前序遍历: [1,3,5,6,2,4]

 

说明: 递归法很简单,你可以使用迭代法完成此题吗?


题目标签:Tree

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 80 ms N/A
/*
// 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 {
private:
    void preorderProcess(Node* cur, vector<int>& res){
        if(!cur) return;
        res.push_back(cur->val);
        for(Node* child : cur->children)
            preorderProcess(child, res);
    }
public:
    vector<int> preorder(Node* root) {
        vector<int> res;
        preorderProcess(root, res);
        return res;
    }
};