776. N-ary Tree Postorder Traversal
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to perform a postorder traversal on an N-ary tree. In a postorder traversal, for any given node, we first recursively visit all its children's subtrees from left to right, and only after all children have been visited, we visit the node itself. The sequence is: Child 1, Child 2, ..., Child N, Root.
Solution
N-ary Tree Postorder Traversal in Python
"""
# Definition for a Node.
class Node:
def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
self.val = val
self.children = children
"""
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
result.append(node.val)
# The Node definition specifies children can be None.
# We must check for this before trying to iterate.
if node.children is not None:
# Extend stack with children. If children are [c1, c2],
# stack becomes [..., c1, c2]. Next pop() gets c2.
# This means children are processed from right to left.
stack.extend(node.children)
# The result list is populated in a modified preorder: (Root, Right, Left).
# Reverse it to get the postorder traversal: (Left, Right, Root).
return result[::-1]
N-ary Tree Postorder Traversal in Java
/*
// Definition for a Node.
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;
}
}
*/
class Solution {
public List<Integer> postorder(Node root) {
// Use a LinkedList for efficient adding to the front (addFirst).
LinkedList<Integer> result = new LinkedList<>();
if (root == null) {
return result;
}
// Stack for iterative traversal.
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node current = stack.pop();
// Add the current node's value to the beginning of the list.
// This effectively reverses the order of insertion.
result.addFirst(current.val);
// Push children onto the stack from left to right.
// Since the stack is LIFO, they will be processed from right to left.
if (current.children != null) { // Safety check for null children list
for (Node child : current.children) {
stack.push(child);
}
}
}
return result;
}
}
N-ary Tree Postorder Traversal in C++
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<int> postorder(Node* root) {
vector<int> result;
if (root == nullptr) {
return result;
}
stack<Node*> s;
s.push(root);
while (!s.empty()) {
Node* current = s.top();
s.pop();
// Add the node's value to the result list.
result.push_back(current->val);
// Push children from left to right onto the stack.
// Because the stack is LIFO, they will be processed from right to left.
for (Node* child : current->children) {
s.push(child);
}
}
// The result is currently in (Root, Right, Left) order.
// Reverse it to get the postorder (Left, Right, Root).
reverse(result.begin(), result.end());
return result;
}
};
N-ary Tree Postorder Traversal in TypeScript
/**
* Definition for node.
* class _Node {
* val: number
* children: _Node[]
* constructor(val?: number) {
* this.val = (val===undefined ? 0 : val)
* this.children = []
* }
* }
*/
function postorder(root: _Node | null): number[] {
if (!root) {
return [];
}
const stack: _Node[] = [root];
const result: number[] = [];
while (stack.length > 0) {
// Pop a node from the stack. The non-null assertion `!` is safe
// because we just checked `stack.length > 0`.
const node = stack.pop()!;
result.push(node.val);
// Push children onto the stack from left to right.
// Since the stack is LIFO, this ensures they're processed right to left.
// The _Node definition ensures `children` is an array, so no null check needed.
for (const child of node.children) {
stack.push(child);
}
}
// The result is in the order of [Root, Rightmost Child, ..., Leftmost Child].
// Reverse it to obtain the postorder traversal: [Leftmost Child, ..., Rightmost Child, Root].
return result.reverse();
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.