Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1829 from AP-Repositories/patch-71
Browse files Browse the repository at this point in the history
Create 0105-construct-binary-tree-from-preorder-and-inorder-traversal.go
  • Loading branch information
Ahmad-A0 authored Jan 1, 2023
2 parents cb06a11 + d901844 commit 95c72a2
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 || len(inorder) == 0 {
return nil
}

root := &TreeNode{Val: preorder[0]}
mid := index(inorder, preorder[0])
root.Left = buildTree(preorder[1: mid + 1], inorder[:mid])
root.Right = buildTree(preorder[mid + 1:], inorder[mid + 1:])
return root
}

func index(arr []int, val int) int {
for i, v := range arr {
if v == val {
return i
}
}
return -1
}

0 comments on commit 95c72a2

Please sign in to comment.