145. Binary Tree Postorder Traversal LeetCode Solution
In this guide, you will get 145. Binary Tree Postorder Traversal LeetCode Solution with the best time and space complexity. The solution to Binary Tree Postorder Traversal problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Binary Tree Postorder Traversal solution in C++
- Binary Tree Postorder Traversal solution in Java
- Binary Tree Postorder Traversal solution in Python
- Additional Resources
Problem Statement of Binary Tree Postorder Traversal
Given the root of a binary tree, return the postorder traversal of its nodes’ values.
Example 1:
Input: root = [1,null,2,3]
Output: [3,2,1]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,6,7,5,2,9,8,3,1]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(h)
145. Binary Tree Postorder Traversal LeetCode Solution in C++
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> ans;
postorder(root, ans);
return ans;
}
private:
void postorder(TreeNode* root, vector<int>& ans) {
if (root == nullptr)
return;
postorder(root->left, ans);
postorder(root->right, ans);
ans.push_back(root->val);
}
};
/* code provided by PROGIEZ */
145. Binary Tree Postorder Traversal LeetCode Solution in Java
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
postorder(root, ans);
return ans;
}
private void postorder(TreeNode root, List<Integer> ans) {
if (root == null)
return;
postorder(root.left, ans);
postorder(root.right, ans);
ans.add(root.val);
}
}
// code provided by PROGIEZ
145. Binary Tree Postorder Traversal LeetCode Solution in Python
class Solution:
def postorderTraversal(self, root: TreeNode | None) -> list[int]:
ans = []
def postorder(root: TreeNode | None) -> None:
if not root:
return
postorder(root.left)
postorder(root.right)
ans.append(root.val)
postorder(root)
return ans
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.