671.second-minimum-node-in-a-binary-tree.go 631 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func findSecondMinimumValue(root *TreeNode) int {
  10. if root == nil {
  11. return -1
  12. }
  13. return helper(root, root.Val)
  14. }
  15. func helper(root *TreeNode, min int) int {
  16. if root.Left == nil {
  17. return -1
  18. }
  19. var l, r int
  20. if root.Left.Val == min {
  21. l = helper(root.Left, min)
  22. } else {
  23. l = root.Left.Val
  24. }
  25. if root.Right.Val == min {
  26. r = helper(root.Right, min)
  27. } else {
  28. r = root.Right.Val
  29. }
  30. switch {
  31. case l == -1:
  32. return r
  33. case r == -1:
  34. return l
  35. case r < l:
  36. return r
  37. }
  38. return l
  39. }