108.go 869 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. // print tree
  6. func printTree(root *TreeNode) {
  7. if root == nil {
  8. return
  9. }
  10. fmt.Print(root.Val, " ")
  11. if root.Left != nil {
  12. printTree(root.Left)
  13. }
  14. if root.Right != nil {
  15. printTree(root.Right)
  16. }
  17. }
  18. type TreeNode struct {
  19. Val int
  20. Left *TreeNode
  21. Right *TreeNode
  22. }
  23. /**
  24. * Definition for a binary tree node.
  25. * type TreeNode struct {
  26. * Val int
  27. * Left *TreeNode
  28. * Right *TreeNode
  29. * }
  30. */
  31. func sortedArrayToBST(nums []int) *TreeNode {
  32. if len(nums) == 0 {
  33. return nil
  34. }
  35. mid := len(nums) / 2
  36. root := TreeNode{nums[mid], nil, nil}
  37. // only one element in nums, return TreeNode{ele, nil, nil}
  38. if mid == 0 {
  39. return &root
  40. }
  41. root.Left = sortedArrayToBST(nums[:mid])
  42. root.Right = sortedArrayToBST(nums[mid+1:])
  43. return &root
  44. }
  45. func main() {
  46. t1 := sortedArrayToBST([]int{-10, -3, 0, 5, 9})
  47. printTree(t1)
  48. }