563.binary-tree-tilt.go 493 B

12345678910111213141516171819202122232425262728293031
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func findTilt(root *TreeNode) int {
  10. tilt := 0
  11. postorder(root, &tilt)
  12. return tilt
  13. }
  14. func postorder(root *TreeNode, tilt *int) int {
  15. if root == nil {
  16. return 0
  17. }
  18. l := postorder(root.Left, tilt)
  19. r := postorder(root.Right, tilt)
  20. sum := l + r + root.Val
  21. *tilt += abs(l - r)
  22. return sum
  23. }
  24. func abs(x int) int {
  25. if x < 0 {
  26. return -x
  27. }
  28. return x
  29. }