Created
June 22, 2018 06:46
-
-
Save chukonu/0ba0d331df2cfa63a9bc0685ab1a0daf to your computer and use it in GitHub Desktop.
Convert sorted arrays to balanced BSTs
This file contains hidden or 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
// xkool 22.06.18 | |
package main | |
import "fmt" | |
type Node struct { | |
Data int | |
Left, Right *Node | |
} | |
func arrayToTree(arr []int, start, end int) (n *Node) { | |
if start > end { | |
return | |
} | |
middle := (start + end) / 2 | |
n = &Node{Data: arr[middle]} | |
n.Left = arrayToTree(arr, start, middle-1) | |
n.Right = arrayToTree(arr, middle+1, end) | |
return | |
} | |
func printPreorder(n *Node) { | |
if n == nil { | |
return | |
} | |
fmt.Println(n.Data) | |
printPreorder(n.Left) | |
printPreorder(n.Right) | |
} | |
func main() { | |
input := []int{1, 2, 3, 4, 5, 6, 7} | |
root := arrayToTree(input, 0, len(input)-1) | |
printPreorder(root) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment