-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path108.将有序数组转换为二叉搜索树.go
87 lines (72 loc) · 1.35 KB
/
108.将有序数组转换为二叉搜索树.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* @lc app=leetcode.cn id=108 lang=golang
*
* [108] 将有序数组转换为二叉搜索树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func sortedArrayToBST(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
if len(nums) == 1 {
return &TreeNode{Val: nums[0]}
}
size := len(nums)
mid := size / 2
low := 0
upper := size
// fmt.Printf("nums are %v, mid is %d, low is %d, upper is %d\n", nums, mid, low, upper)
root := &TreeNode{Val: nums[mid]}
if low < mid {
tmp := sortedArrayToBST(nums[low: mid])
root.Left = tmp
}
if upper > mid {
tmp := sortedArrayToBST(nums[mid+1: upper])
root.Right = tmp
}
return root
}
// @lc code=end
func print(root *TreeNode){
if root == nil {
return
}
stack := []*TreeNode{}
stack = append(stack, root)
for len(stack) > 0 {
size := len(stack)
for i := 0 ; i < size ; i++ {
tmp := stack[0]
stack = stack[1:]
fmt.Printf("%d ", tmp.Val)
if tmp.Left != nil {
stack = append(stack, tmp.Left)
}
if tmp.Right != nil {
stack = append(stack, tmp.Right)
}
}
fmt.Println()
}
}
func main(){
a := []int{-10,-3,0,5,9}
b := sortedArrayToBST(a)
print(b)
}