Solution for leetcode 105
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
class Solution {
HashMap<Integer,Integer> map = new HashMap();
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = inorder.length;
for(int i = 0; i < n; i++){
map.put(inorder[i], i);
}
return dfs(preorder, inorder, 0, n - 1, 0, n - 1);
}
public TreeNode dfs(int[] preorder, int[] inorder, int preleft, int preright, int inleft, int inright){
if(preleft > preright){
return null;
}
TreeNode root = new TreeNode(preorder[preleft]);
int inIndex = map.get(preorder[preleft]);
int leftSize = inIndex - inleft;
int rightSize = inorder.length - leftSize;
root.left = dfs(preorder, inorder, preleft + 1, preleft + leftSize, inleft, inIndex - 1 );
root.right = dfs(preorder, inorder, preleft + leftSize + 1,preright,inIndex + 1, inright);
return root;
}
}
Solution for leetcode 106
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
class Solution {
Map<Integer, Integer> map = new HashMap();
public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = inorder.length;
for(int i = 0; i < n; i++){
map.put(inorder[i], i);
}
return dfs(inorder, postorder, 0, n - 1, 0, n - 1);
}
public TreeNode dfs(int[] inorder, int[] postorder, int inleft, int inright, int postleft, int postright){
if(inleft > inright){
return null;
}
TreeNode node = new TreeNode(postorder[postright]);
int inIndex = map.get(postorder[postright]);
int rightSize = inright - inIndex;
node.left = dfs(inorder, postorder, inleft, inIndex - 1, postleft, postright - 1 - rightSize);
node.right = dfs(inorder, postorder, inIndex + 1, inright, postright - rightSize ,postright - 1);
return node;
}
}
Solution for leetcode 1008
https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
class Solution {
public TreeNode bstFromPreorder(int[] preorder) {
int n = preorder.length;
return dfs(preorder, 0, n - 1);
}
public TreeNode dfs(int[] preorder, int preleft, int preright){
if(preleft > preright){
return null;
}
int cur = preorder[preleft];
TreeNode root = new TreeNode(cur);
int newright = preleft + 1;
if(preleft + 1 <= preright){
while(newright <= preright){
if(preorder[newright] > cur){
break;
}
newright++;
}
}
root.left = dfs(preorder, preleft + 1, newright - 1);
root.right = dfs(preorder, newright, preright);
return root;
}
}