问题

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

例如,给定一个 3叉树 :

C#LeetCode刷题之#589-N叉树的前序遍历(N-ary Tree Preorder Traversal)

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

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


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

 For example, given a 3-ary tree:

C#LeetCode刷题之#589-N叉树的前序遍历(N-ary Tree Preorder Traversal)

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

 Note: Recursive solution is trivial, could you do it iteratively?


示例

public class Program {

    public static void Main(string[] args) {
        var root = new Node(1,
                new List<Node> {
                new Node(3, new List<Node> {
                    new Node(5, null),
                    new Node(6, null)
                }),
                new Node(2, null),
                new Node(4, null)
            });

        var res = Preorder(root);
        ShowArray(res);

        res = Preorder2(root);
        ShowArray(res);

        Console.ReadKey();
    }

    private static void ShowArray(IList<int> array) {
        foreach(var num in array) {
            Console.Write($"{num} ");
        }
        Console.WriteLine();
    }

    public static IList<int> Preorder(Node root) {
        var list = new List<int>();
        Pre(root, ref list);
        return list;
    }

    public static void Pre(Node root, ref List<int> list) {
        if(root == null) return;
        list.Add(root.val);
        if(root.children == null) return;
        foreach(var child in root.children) {
            Pre(child, ref list);
        }
        return;
    }

    public static IList<int> Preorder2(Node root) {
        var list = new List<int>();
        if(root == null) return list;
        var stack = new Stack<Node>();
        stack.Push(root);
        while(stack.Any()) {
            var pop = stack.Pop();
            list.Add(pop.val);
            if(pop.children != null) {
                for(var i = pop.children.Count() - 1; i >= 0; i--)
                    stack.Push(pop.children[i]);
            }
        }
        return list;
    }

    public class Node {
        public int val;
        public IList<Node> children;
        public Node() { }
        public Node(int _val, IList<Node> _children) {
            val = _val;
            children = _children;
        }
    }

}

以上给出2种算法实现,以下是这个案例的输出结果:

1 3 5 6 2 4
1 3 5 6 2 4

分析:

显而易见,以上2种算法的时间复杂度均为: C#LeetCode刷题之#589-N叉树的前序遍历(N-ary Tree Preorder Traversal) 。

相关文章:

  • 2022-02-10
  • 2021-07-28
  • 2021-07-13
  • 2022-01-18
  • 2021-10-19
  • 2021-07-26
  • 2021-08-25
猜你喜欢
  • 2021-10-15
  • 2021-06-28
  • 2021-09-16
  • 2021-10-24
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案