783. 二叉搜索树节点最小距离

image.png

  1. package main
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. )
  7. type TreeNode struct {
  8. Val int
  9. Left *TreeNode
  10. Right *TreeNode
  11. }
  12. // 中序遍历
  13. func minDiffInBST(root *TreeNode) int {
  14. var res []int
  15. stack := make([]*TreeNode,0)
  16. for root!=nil||len(stack)>0{
  17. for root!=nil{
  18. stack = append(stack,root)
  19. root =root.Left
  20. }
  21. node :=stack[len(stack)-1]
  22. stack = stack[:len(stack)-1]
  23. res = append(res,node.Val)
  24. root = node.Right
  25. }
  26. if len(res)<2 {
  27. return res[0]
  28. }
  29. min :=res[1]-res[0]
  30. for i:=2;i<len(res);i++{
  31. r := res[i]-res[i-1]
  32. if min>r{
  33. min = r
  34. }
  35. }
  36. return min
  37. }
  38. func BuildBinaryTree(src string)*TreeNode{
  39. src =src[1:len(src)-1]
  40. strList := strings.Split(src, ",")
  41. var currNode *TreeNode
  42. var root *TreeNode
  43. var queue []*TreeNode
  44. for i :=0;i<len(strList);i+=2{
  45. if i==0 {
  46. v,_:=strconv.Atoi(strList[i])
  47. currNode =&TreeNode{Val:v}
  48. root =currNode
  49. queue = append(queue,currNode)
  50. }
  51. if len(queue)>0 {
  52. currNode =queue[0]
  53. queue =queue[1:]
  54. }else {
  55. break
  56. }
  57. if i+1<len(strList)&&strList[i+1]!="null"{
  58. v,_:=strconv.Atoi(strList[i+1])
  59. currNode.Left = &TreeNode{Val:v}
  60. queue = append(queue,currNode.Left)
  61. }
  62. if i+2<len(strList)&&strList[i+2]!="null"{
  63. v,_:=strconv.Atoi(strList[i+2])
  64. currNode.Right = &TreeNode{Val:v}
  65. queue = append(queue,currNode.Right)
  66. }
  67. }
  68. return root
  69. }
  70. func main() {
  71. root := BuildBinaryTree("[4,2,6,1,3,null,null]")
  72. fmt.Println(minDiffInBST(root))
  73. root1 :=BuildBinaryTree("[27,null,34,null,58,50,null,44,null,null,null]")
  74. fmt.Println(minDiffInBST(root1))
  75. }

image.png