LeetCode Top Interview 150

105. Construct Binary Tree from Preorder and Inorder Traversal

Medium

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

Example 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]

Output: [3,9,20,null,null,15,7]

Example 2:

Input: preorder = [-1], inorder = [-1]

Output: [-1]

Constraints:

Solution

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func buildTree(preorder []int, inorder []int) *TreeNode {
	inorderIndexMap := make(map[int]int)
	for i, value := range inorder {
		inorderIndexMap[value] = i
	}
	var build func(preStart, preEnd, inStart, inEnd int) *TreeNode
	build = func(preStart, preEnd, inStart, inEnd int) *TreeNode {
		if preStart > preEnd {
			return nil
		}

		rootVal := preorder[preStart]
		root := &TreeNode{Val: rootVal}
		inRootIndex := inorderIndexMap[rootVal]

		leftTreeSize := inRootIndex - inStart
		root.Left = build(preStart+1, preStart+leftTreeSize, inStart, inRootIndex-1)
		root.Right = build(preStart+leftTreeSize+1, preEnd, inRootIndex+1, inEnd)
		return root
	}
	return build(0, len(preorder)-1, 0, len(inorder)-1)
}