111.go 1020 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type TreeNode struct {
  6. Val int
  7. Left *TreeNode
  8. Right *TreeNode
  9. }
  10. func minInt(x, y int) int {
  11. if x < y {
  12. return x
  13. }
  14. return y
  15. }
  16. func minDepthIter(root *TreeNode, depth int) int {
  17. if root.Left == nil && root.Right == nil {
  18. return depth
  19. }
  20. if root.Left == nil {
  21. return minDepthIter(root.Right, depth+1)
  22. }
  23. if root.Right == nil {
  24. return minDepthIter(root.Left, depth+1)
  25. }
  26. return minInt(minDepthIter(root.Left, depth+1), minDepthIter(root.Right, depth+1))
  27. }
  28. /**
  29. * Definition for a binary tree node.
  30. * type TreeNode struct {
  31. * Val int
  32. * Left *TreeNode
  33. * Right *TreeNode
  34. * }
  35. */
  36. func minDepth(root *TreeNode) int {
  37. if root == nil {
  38. return 0
  39. }
  40. return minDepthIter(root, 1)
  41. }
  42. func main() {
  43. /**
  44. * t1: 5
  45. * \
  46. * 4
  47. * / \
  48. * 2 3
  49. */
  50. t1rl := TreeNode{2, nil, nil}
  51. t1rr := TreeNode{3, nil, nil}
  52. t1r := TreeNode{4, &t1rl, &t1rr}
  53. t1 := &TreeNode{5, nil, &t1r}
  54. fmt.Println(minDepth(t1))
  55. fmt.Println(minDepth(nil))
  56. }