zoukankan      html  css  js  c++  java
  • (N叉树 递归) 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?

    ---------------------------------------------------------------------------------------------------------------------------------

    额,这个迭代不会,不过,如果会了二叉树的前序遍历的递归解法的话,解这个题就会感觉简单了,同理,后序遍历也是,不过,中序遍历上可能会很难写。

    C++代码:

    /*
    // 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> res;
            helper(root,res);
            return res;
        }
        void helper(Node *root,vector<int> &res){
            if(!root) return;
            res.push_back(root->val);
            for(Node* cur : root->children){
                helper(cur,res);
            }
        }
    };
  • 相关阅读:
    hdu 3996
    poj 3189
    poj 2391
    zoj 3165
    【Visual Studio】
    httpwebrequest Winform 上传图片
    [MVC] win7 下 配置 IIS 问题
    win7 下 升级 vs2008
    [Visual Studio 2010] NET 4.0 WinForm无法引用System.Web.dll的解决方法
    [XML] XML
  • 原文地址:https://www.cnblogs.com/Weixu-Liu/p/10776096.html
Copyright © 2011-2022 走看看