
Sponsored
Sponsored
The simplest way to perform a postorder traversal of a binary tree is recursively. In postorder traversal, you need to traverse the left subtree, then traverse the right subtree, finally visit the root node. This means visiting the left child, then the right child, and then the node itself for each node in the tree.
Time Complexity: O(n), where n is the number of nodes in the binary tree, because each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack usage.
1class TreeNode:
2 def __init__(self, x):
3 self.val = x
4 self.left = None
5 self.right = None
6
7class Solution:
8 def postorderTraversal(self, root: TreeNode) -> List[int]:
9 result = []
10 self.postorderHelper(root, result)
11 return result
12
13 def postorderHelper(self, node: TreeNode, result: List[int]):
14 if node:
15 self.postorderHelper(node.left, result)
16 self.postorderHelper(node.right, result)
17 result.append(node.val)The Python solution recursively traverses the binary tree in a postorder style using a helper function, postorderHelper. Once it has traversed both the left and right children nodes, it appends the current node's value to the results list.
To perform postorder traversal iteratively, two stacks can be used. The first stack is used to perform a modified preorder traversal (root-right-left), while the second stack reverses this order to provide the postorder traversal (left-right-root). This approach allows the sequence of visiting nodes in postorder traversal without recursion.
Time Complexity: O(n) where n is the number of nodes.
Space Complexity: O(n) due to the usage of two stacks, each containing n nodes in the worst case for balanced or full trees.
This JavaScript solution circumvents recursion by employing two stacks to process the tree. The initial stack (stack1) uses root-right-left sequence collecting nodes, which are subsequently popped from stack2 in reversed order to deliver a left-right-root traversal sequence.