590. N叉树的后序遍历
590. N-ary Tree Postorder Traversal题目描述
给定一个 N 叉树,返回其节点值的后序遍历。LeetCode590. N-ary Tree Postorder Traversal
例如,给定一个 3 叉树:
说明: 递归法很简单,你可以使用迭代法完成此题吗?
Java 实现
Iterative Solutionimport java.util.LinkedList;import java.util.List;import java.util.Stack;class Node { public int val; public Listchildren; public Node() { } public Node(int _val, List _children) { val = _val; children = _children; }}class Solution { public List postorder(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(); for (Node child:node.children){ stack.push(child); } result.add(0, node.val); } return result; }}
Recursive Solution
import java.util.LinkedList;import java.util.List;class Node { public int val; public Listchildren; public Node() { } public Node(int _val, List _children) { val = _val; children = _children; }}class Solution { List result = new LinkedList<>(); public List postorder(Node root) { if (root == null) { return result; } List node = root.children; for (int i = 0; i < node.size(); i++) { postorder(node.get(i)); } result.add(root.val); return result; }}
相似题目
参考资料