Given the root of an N-ary tree, return the postorder traversal of its nodes’ values.
N-ary Tree: In an N-ary tree, a node can have at most N children.
Example:
Input: root = [1,null,3,2,4,null,5,6]
Output: [5,6,3,2,4,1]
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
[0, 10^4]
.[0, 10^4]
.The postorder traversal visits each node’s children before visiting the node itself. This can be naturally implemented using recursion, but an iterative approach is also possible using a stack.
postOrderTraversal
that takes a node and a result list.class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
class Solution:
def postorder(self, root: 'Node') -> List[int]:
def traverse(node, result):
if node is None:
return
for child in node.children:
traverse(child, result)
result.append(node.val)
result = []
traverse(root, result)
return result
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
class Solution:
def postorder(self, root: 'Node') -> List[int]:
if not root:
return []
stack, result = [root], []
while stack:
node = stack.pop()
result.append(node.val)
for child in node.children:
stack.append(child)
return result[::-1]
Both the recursive and iterative solutions have a time complexity of (O(N)), where (N) is the number of nodes in the tree. This is because each node is visited exactly once.
In summary, both solutions are efficient and appropriate for the given problem constraints. The choice between the two may depend on the preferred style (recursive vs. iterative).
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?