110.go 1.0 KB

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