589. N叉树的前序遍历
589. N-ary Tree Preorder Traversal
LeetCode589. N-ary Tree Preorder Traversal
题目描述
给定一个 N 叉树,返回其节点值的前序遍历。
例如,给定一个 3 叉树 :
返回其前序遍历: [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<Node> children; public Node() { } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } class Solution { public List<Integer> preorder(Node root) { List<Integer> result = new LinkedList<>(); if (root == null) { return result; } Stack<Node> 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<Node> children; public Node() { } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } class Solution { List<Integer> result = new LinkedList<>(); public List<Integer> preorder(Node root) { if (root == null) { return result; } result.add(root.val); List<Node> node = root.children; for (int i = 0; i < node.size(); i++) { preorder(node.get(i)); } return result; } }
相似题目
参考资料
- https://leetcode.com/problems/n-ary-tree-preorder-traversal/
- https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/
来源:https://www.cnblogs.com/hglibin/p/10850026.html