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

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

LeetCode589. N-ary Tree Preorder Traversal

题目描述
给定一个 N 叉树,返回其节点值的前序遍历。

例如,给定一个 3 叉树 :

LeetCode 589. N叉树的前序遍历(N-ary Tree Preorder Traversal)_第1张图片
返回其前序遍历: [1,3,5,6,2,4]。

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

Java 实现
Iterative Solution

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

class Node {
    public int val;
    public List children;

    public Node() {
    }

    public Node(int _val, List _children) {
        val = _val;
        children = _children;
    }
}

class Solution {
    public List preorder(Node root) {
        List result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        Stack stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            if (node.children != null) {
                for (int i = node.children.size() - 1; i >= 0; i--) {
                    stack.push(node.children.get(i));
                }
            }
            result.add(node.val);
        }
        return result;
    }
}

Recursive Solution

import java.util.LinkedList;
import java.util.List;

class Node {
    public int val;
    public List children;

    public Node() {
    }

    public Node(int _val, List _children) {
        val = _val;
        children = _children;
    }
}

class Solution {
    List result = new LinkedList<>();

    public List preorder(Node root) {
        if (root == null) {
            return result;
        }
        result.add(root.val);
        List node = root.children;
        for (int i = 0; i < node.size(); i++) {
            preorder(node.get(i));
        }
        return result;
    }
}

相似题目

  • 144. 二叉树的前序遍历
  • 429. N叉树的层序遍历
  • 590. N叉树的后序遍历

参考资料

  • https://leetcode.com/problems/n-ary-tree-preorder-traversal/
  • https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/

你可能感兴趣的:(LeetCode 589. N叉树的前序遍历(N-ary Tree Preorder Traversal))