12345678910111213141516171819202122232425262728293031 |
- /**
- * Definition for a binary tree node.
- * type TreeNode struct {
- * Val int
- * Left *TreeNode
- * Right *TreeNode
- * }
- */
- func findTilt(root *TreeNode) int {
- tilt := 0
- postorder(root, &tilt)
- return tilt
- }
- func postorder(root *TreeNode, tilt *int) int {
- if root == nil {
- return 0
- }
- l := postorder(root.Left, tilt)
- r := postorder(root.Right, tilt)
- sum := l + r + root.Val
- *tilt += abs(l - r)
- return sum
- }
- func abs(x int) int {
- if x < 0 {
- return -x
- }
- return x
- }
|