530. 二叉搜索树的最小绝对差

image.png
中序遍历递归实现

  1. var pre *TreeNode
  2. var res int
  3. func dfs(root *TreeNode){
  4. if root==nil{
  5. return
  6. }
  7. dfs(root.Left)
  8. if pre!=nil {
  9. res = int(math.Min(math.Abs(float64(root.Val-pre.Val)),float64(res)))
  10. }
  11. pre = root
  12. dfs(root.Right)
  13. }
  14. func getMinimumDifference(root *TreeNode) int {
  15. res = math.MaxInt32
  16. dfs(root)
  17. return res
  18. }
  19. func main() {
  20. root :=&TreeNode{Val: 1}
  21. two :=&TreeNode{Val: 2}
  22. three :=&TreeNode{Val: 3}
  23. root.Right = three
  24. three.Left = two
  25. fmt.Println(getMinimumDifference(root))
  26. }

image.png