145. Binary Tree Postorder Traversal #400
-
Difficulty: Easy Topics: Given the Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use an iterative approach with a stack. Postorder traversal follows the order: Left, Right, Root. Let's implement this solution in PHP: 145. Binary Tree Postorder Traversal <?php
// Definition for a binary tree node.
class TreeNode {
public $val = null;
public $left = null;
public $right = null;
public function __construct($val = 0, $left = null, $right = null) {
$this->val = $val;
$this->left = $left;
$this->right = $right;
}
}
function postorderTraversal($root) {
$result = [];
if ($root === null) {
return $result;
}
$stack = [];
$lastVisitedNode = null;
$current = $root;
while (!empty($stack) || $current !== null) {
if ($current !== null) {
array_push($stack, $current);
$current = $current->left;
} else {
$peekNode = end($stack);
// if right child exists and traversing node from left child, then move right
if ($peekNode->right !== null && $lastVisitedNode !== $peekNode->right) {
$current = $peekNode->right;
} else {
array_push($result, $peekNode->val);
$lastVisitedNode = array_pop($stack);
}
}
}
return $result;
}
// Example usage:
// Example 1
$root1 = new TreeNode(1);
$root1->right = new TreeNode(2);
$root1->right->left = new TreeNode(3);
print_r(postorderTraversal($root1)); // Output: [3, 2, 1]
// Example 2
$root2 = null;
print_r(postorderTraversal($root2)); // Output: []
// Example 3
$root3 = new TreeNode(1);
print_r(postorderTraversal($root3)); // Output: [1]
?> Explanation:
This iterative approach simulates the recursive postorder traversal without using system recursion, making it more memory-efficient. |
Beta Was this translation helpful? Give feedback.
We can use an iterative approach with a stack. Postorder traversal follows the order: Left, Right, Root.
Let's implement this solution in PHP: 145. Binary Tree Postorder Traversal