145. Binary Tree Postorder Traversal
Difficulty: Easy
Topics: Stack, Tree, Depth-First Search, Binary Tree
Given the root of a binary tree, return the postorder traversal of its nodes' values.
Example 1:
Example 2:
Example 3:
Constraints:
Solution:
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
val = $val; $this->left = $left; $this->right = $right; } } /** * @param TreeNode $root * @return Integer[] */ function postorderTraversal($root) { ... ... ... /** * go to ./solution.php */ } // 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:
TreeNode Class: The TreeNode class defines a node in the binary tree, including its value, left child, and right child.
postorderTraversal Function:
This iterative approach simulates the recursive postorder traversal without using system recursion, making it more memory-efficient.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Binary Tree Postorder Traversal. For more information, please follow other related articles on the PHP Chinese website!