145. Binary Tree Postorder Traversal
Difficulty:Easy
Topics:Stack, Tree, Depth-First Search, Binary Tree
Given the root of a binary tree, returnthe 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 therepositorya 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:
위 내용은 . 이진 트리 후위 순회의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!