110.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. // type TreeNode struct {
  3. // Val int
  4. // Left *TreeNode
  5. // Right *TreeNode
  6. // }
  7. // func maxInt(x, y int) int {
  8. // if x > y {
  9. // return x
  10. // }
  11. // return y
  12. // }
  13. // func abs(x int) int {
  14. // if x < 0 {
  15. // return -x
  16. // }
  17. // return x
  18. // }
  19. func treeDepth(root *TreeNode, depth int) int {
  20. if root == nil {
  21. return depth
  22. }
  23. return maxInt(treeDepth(root.Left, depth+1), treeDepth(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 isBalanced(root *TreeNode) bool {
  34. if root == nil {
  35. return true
  36. }
  37. if abs(treeDepth(root.Left, 0)-treeDepth(root.Right, 0)) > 1 {
  38. return false
  39. }
  40. return isBalanced(root.Left) && isBalanced(root.Right)
  41. }
  42. // func main() {
  43. // /**
  44. // * t1: 5
  45. // * / \
  46. // * 1 4
  47. // * / \
  48. // * 2 3
  49. // */
  50. // t1l := TreeNode{1, nil, nil}
  51. // t1rl := TreeNode{2, nil, nil}
  52. // t1rr := TreeNode{3, nil, nil}
  53. // t1r := TreeNode{4, &t1rl, &t1rr}
  54. // t1 := &TreeNode{5, &t1l, &t1r}
  55. // fmt.Println(isBalanced(t1))
  56. // fmt.Println(isBalanced(nil))
  57. // }