-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbalance_bin_tree.go
48 lines (41 loc) · 920 Bytes
/
balance_bin_tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// https://leetcode.com/problems/balance-a-binary-search-tree/
package main
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func NewTree(arr []int) *TreeNode {
l := len(arr)
if l == 1 {
return &TreeNode{Val: arr[0]}
}
mid := l / 2
mid_val := arr[mid]
left_nodes := arr[:mid]
var left_tree *TreeNode
if len(left_nodes) > 0 {
left_tree = NewTree(left_nodes)
}
right_nodes := arr[mid+1:]
var righ_tree *TreeNode
if len(right_nodes) > 0 {
righ_tree = NewTree(right_nodes)
}
return &TreeNode{Val: mid_val, Left: left_tree, Right: righ_tree}
}
func VisitInOrder(root *TreeNode, arr *[]int) {
if root.Left != nil {
VisitInOrder(root.Left, arr)
}
*arr = append(*arr, root.Val)
if root.Right != nil {
VisitInOrder(root.Right, arr)
}
}
//lint:ignore U1000 Ignore
func balanceBST(root *TreeNode) *TreeNode {
arr := []int{}
VisitInOrder(root, &arr)
return NewTree(arr)
}