algoadvance

Leetcode 590. N

Problem Statement

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;
    }
}

Clarifying Questions

  1. What is a postorder traversal?
    • Postorder traversal is a type of depth-first traversal where you visit each node in the order: children first, then the node itself.
  2. Can the tree be empty?
    • Yes, the tree can be empty, in which case the result should be an empty list.
  3. Are there any constraints on the values of the nodes?
    • No specific constraints provided on node values except that they are integers.

Strategy

  1. Recursive Approach: Use a helper function to perform a recursive postorder traversal.
    • Traverse each child node first.
    • Append the current node’s value to the result list after traversing all of its children.
    • This ensures children of each node will be visited before the node itself.
  2. Iterative Approach: Use a stack to simulate the postorder traversal.
    • A stack is used to keep track of nodes, and another list or stack is used to store the output in reversed order (since postorder can be considered as reverse of some specific preorder traversal).
    • This method is more complex but can be useful in cases where recursion depth might be an issue.

Code

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);
    }
}

Time Complexity

This approach ensures a clear and efficient traversal of the n-ary tree in postorder fashion.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI