MrainW's Home

All things come to those who wait!

0%

LeetCode 145. Binary Tree Postorder Traversal

Question

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Example 1:

1
2
Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:

1
2
Input: root = []
Output: []

Example 3:

1
2
Input: root = [1,2]
Output: [2,1]

Solution

  • Solution1 – iterative
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if(root != null) stack.push(root);
while(!stack.isEmpty()){
root = stack.pop();
res.add(0, root.val);
if(root.left != null) stack.push(root.left);
if(root.right != null) stack.push(root.right);
}
return res;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

  • Solution2 – recursive
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
helper(root, res);
return res;
}
private void helper(TreeNode root, List<Integer> res) {
if (root == null) return;
helper(root.left, res);
helper(root.right, res);
res.add(root.val);
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels