LeetCode Solutions
145. Binary Tree Postorder Traversal
Time: $O(n)$ Space: $O(h)$
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);
}
};
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);
}
}
class Solution:
def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def postorder(root: Optional[TreeNode]) -> None:
if not root:
return
postorder(root.left)
postorder(root.right)
ans.append(root.val)
postorder(root)
return ans