MrainW's Home

All things come to those who wait!

0%

LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal

Question

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

Example 1:

1
2
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

1
2
Input: inorder = [-1], postorder = [-1]
Output: [-1]

Solution

  • Solution1 – postorder traversal, inorder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int[] inorder;
int[] postorder;
int N;
Map<Integer, Integer> inMap = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.inorder = inorder;
this.postorder = postorder;
N = inorder.length;
for (int i = 0; i < N; i++) inMap.put(inorder[i], i);
return helper(0, N - 1, 0, N - 1);
}
public TreeNode helper(int inStart, int inEnd, int postStart, int postEnd){
if (inStart > inEnd) return null;
TreeNode root = new TreeNode(postorder[postEnd]);
int inIndex = inMap.get(root.val);
int rightTreeSize = inEnd - inIndex;
root.left = helper(inStart, inIndex - 1, postStart, postEnd - rightTreeSize -1);
root.right = helper(inIndex + 1, inEnd, postEnd - rightTreeSize, postEnd -1);
return root;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(n)

Welcome to my other publishing channels