111.go 1.1 KB

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