luoheng
10/26/2019 - 4:24 AM

findTilt

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

import "math"

func order(root *TreeNode) (sumVal, sumTilt int) {
    if root == nil {
        return
    }
    leftSum, leftTilt := order(root.Left)
    rightSum, rightTilt := order(root.Right)
    sumVal = leftSum + rightSum + root.Val
    sumTilt = leftTilt + rightTilt + int(math.Abs(float64(leftSum - rightSum)))
    return
}

func findTilt(root *TreeNode) int {
    _, sumTilt := order(root)
    return sumTilt
}