Given an n-ary
tree, return the postorder traversal of its nodes’ values.
In an n-ary
tree, each node has 0 or more children. Each node is represented as Node
class with the following attributes:
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;
}
}
Let’s start with the recursive approach for simplicity.
import java.util.ArrayList;
import java.util.List;
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;
}
}
public class Solution {
public List<Integer> postorder(Node root) {
List<Integer> result = new ArrayList<>();
postorderHelper(root, result);
return result;
}
private void postorderHelper(Node node, List<Integer> result) {
if (node == null) {
return;
}
for (Node child : node.children) {
postorderHelper(child, result);
}
result.add(node.val);
}
}
This approach ensures a clear and efficient traversal of the n-ary tree in postorder fashion.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?