def helper(pre_order, cur_idx=0, min=float('-inf'), max=float('inf')): if cur_idx >= len(pre_order): return None, 0 cur_node = BinaryNode(pre_order[cur_idx]) cur_idx += 1 if cur_idx < len(pre_order) and min <= pre_order[cur_idx] <= cur_node.data: cur_node.left, cur_idx = helper(pre_order, cur_idx, min, cur_node.data) if cur_idx < len(pre_order) and cur_node.data < pre_order[cur_idx] <= max: cur_node.right, cur_idx = helper(pre_order, cur_idx, cur_node.data, max) return cur_node, cur_idx
def make_tree(pre_remaining, in_map, in_start=0, in_end=None): # End index exclusive if not in_end: in_end = len(pre_remaining) if not pre_remaining or in_map[pre_remaining[0]] >= in_end or in_start >= in_end: return None cur_node = BinaryNode(pre_remaining.popleft()) left_end = in_map[cur_node.data] + 1 cur_node.left = make_tree(pre_remaining, in_start, left_end) cur_node.right = make_tree(pre_remaining, left_end, in_end) return cur_node