105. Construct Binary Tree from Preorder and Inorder Traversal
https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
Python
First try
A correct solutions but did not get benfit from Python List slide
from typing import List, Optional
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
return self._build(
preorder=preorder,
pre_start=0,
pre_end=len(preorder)-1,
inorder=inorder,
in_start=0,
in_end=len(inorder)-1
)
def _build(self, preorder: List[int], pre_start: int, pre_end: int,
inorder: List[int], in_start: int, in_end: int):
if pre_start > pre_end:
return None
root_val = preorder[pre_start]
root_index = inorder.index(root_val)
left_size = root_index - in_start
return TreeNode(
val=root_val,
left=self._build(
preorder=preorder,
pre_start=pre_start+1,
pre_end=pre_start+left_size,
inorder=inorder,
in_start=in_start,
in_end=root_index-1
),
right=self._build(
preorder=preorder,
pre_start=pre_start+left_size+1,
pre_end=pre_end,
inorder=inorder,
in_start=root_index+1,
in_end=in_end
)
)
Second try
Solution which more Pythonic
from typing import List
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
if not preorder or not inorder:
return
root_val = preorder[0]
root_index = inorder.index(root_val)
return TreeNode(
val=root_val,
left=self.buildTree(
preorder[1:],
inorder[0:root_index]
),
right=self.buildTree(
preorder[root_index+1:],
inorder[root_index+1:]
)
)
Javscript
var buildTree = function(preorder, inorder) {
const hashmap = new Map(inorder.map((val, idx) => [val, idx]));
const constructTree = (start, end) => {
if (start > end) return null;
const value = preorder.shift();
const index = hashmap.get(value);
const root = new TreeNode(value);
root.left = constructTree(start, index - 1);
root.right = constructTree(index + 1, end);
return root;
}
return constructTree(0, preorder.length - 1);
};