Sponsored
Sponsored
This approach utilizes recursion to traverse the N-ary tree in a postorder fashion. For each node, we recursively visit all its children first before processing the node itself.
Time Complexity: O(n), where n is the number of nodes, as each node is visited once.
Space Complexity: O(n) for the recursion stack in the worst case (maximum tree height).
1import java.util.*;
2
3class Node {
4 public int val;
5 public List<Node> children;
6
7 public Node() {}
8
9 public Node(int _val) {
10 val = _val;
11 }
12
13 public Node(int _val, List<Node> _children) {
14 val = _val;
15 children = _children;
16 }
17};
18
19class Solution {
20 public List<Integer> postorder(Node root) {
21 List<Integer> result = new ArrayList<>();
22 postorderHelper(root, result);
23 return result;
24 }
25
26 private void postorderHelper(Node node, List<Integer> result) {
27 if (node == null) return;
28 for (Node child : node.children) {
29 postorderHelper(child, result);
30 }
31 result.add(node.val);
32 }
33}
34
The Java solution utilizes a similar approach with a helper function, postorderHelper
, which manages the recursion. This function processes children first, appending the node value to the result list afterwards. The main method postorder
collects the results after traversing the tree.
This approach uses an iterative method to perform postorder traversal with the help of a stack to simulate recursion. Nodes are pushed onto the stack in such a way that their children are processed before the node itself.
Time Complexity: O(n)
Space Complexity: O(n)
1#
This C solution uses a stack to hold nodes and their visitation state. Nodes are pushed onto the stack to revisit them later for value recording, ensuring that each node's children are processed before the node itself, mimicking postorder traversal.