530.minimum-absolute-difference-in-bst.go 602 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. var pre int = 0
  2. var ini bool = false
  3. /**
  4. * Definition for a binary tree node.
  5. * type TreeNode struct {
  6. * Val int
  7. * Left *TreeNode
  8. * Right *TreeNode
  9. * }
  10. */
  11. func getMinimumDifference(root *TreeNode) (diff int) {
  12. pre, diff = 0, 1<<32-1
  13. ini = false
  14. inorder(root, &diff)
  15. return
  16. }
  17. func inorder(root *TreeNode, diff *int) {
  18. if root == nil {
  19. return
  20. }
  21. inorder(root.Left, diff)
  22. if ini {
  23. d := abs(root.Val - pre)
  24. if d < *diff {
  25. *diff = d
  26. }
  27. } else {
  28. ini = true
  29. }
  30. pre = root.Val
  31. inorder(root.Right, diff)
  32. }
  33. func abs(x int) int {
  34. if x < 0 {
  35. return -x
  36. }
  37. return x
  38. }