0589. N Ary Tree Preorder Traversal

589. N-ary Tree Preorder Traversal #

题目 #

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

思路 #

  • 递归
  • 迭代

代码 #

递归 #

class Node {
    public int val;
    public List<Node> children;
    
    public Node() {}
    public Node(int _val) { val = _val; }
    public Node(int _val, List<Node> _children) { val = _val; children = _children; }
}
class Solution {
    public void traversal(Node root, List<Integer> ans) {
        if (root == null) return;
        ans.add(root.val);
        for (Node child: root.children) traversal(child, ans);
    }
    public List<Integer> preorder(Node root) {
        List<Integer> ans = new LinkedList<>();
        
        traversal(root, ans);
        
        return ans;
    }
}

迭代 #