104.go 843 B

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