Created
November 24, 2022 07:28
-
-
Save creative-cranels/2721abf673c2da62a9315ed488b8a60c to your computer and use it in GitHub Desktop.
108. Convert Sorted Array to Binary Search Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* type TreeNode struct { | |
* Val int | |
* Left *TreeNode | |
* Right *TreeNode | |
* } | |
*/ | |
func sortedArrayToBST(nums []int) *TreeNode { | |
length := len(nums) | |
// fmt.Printf("nums: %v\n", nums) | |
// fmt.Printf("length: %d\n", length) | |
if length == 0 { | |
// fmt.Printf("\n\n") | |
return nil | |
} | |
if length == 1 { | |
// fmt.Printf("\n\n") | |
return &TreeNode { | |
Val: nums[0], | |
} | |
} | |
center := length / 2 | |
lr := center - 1 | |
rl := center + 1 | |
// fmt.Printf("center: %d\n", center) | |
// fmt.Printf("left: %d %d\n", ll, lr) | |
// fmt.Printf("right: %d %d\n", rl, rr) | |
// fmt.Printf("\n\n") | |
root := &TreeNode { | |
Val: nums[center], | |
Left: sortedArrayToBST(nums[:lr+1]), | |
Right: sortedArrayToBST(nums[rl:]), | |
} | |
return root | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment