/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTilt(root *TreeNode) int {
ans := 0
var dfs func(*TreeNode) int
dfs = func(node *TreeNode) int {
if(node == nil){
return 0
}
l := dfs(node.Left)
r := dfs(node.Right)
if v := l - r ; v > 0 {
ans += v
} else {
ans -= v
}
return l + r + node.Val
}
dfs(root)
return ans
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTilt(root *TreeNode) int {
if root == nil {
return 0
}
return getMax(sum(root.Left), sum(root.Right)) + findTilt(root.Left) + findTilt(root.Right)
}
// 所有节点之和
func sum(root *TreeNode) int {
if root == nil {
return 0
}
return root.Val + sum(root.Left) + sum(root.Right)
}
func getMax(a, b int) int {
if a > b {
return a - b
}
return b - a
}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findTilt(root *TreeNode) int {
if root == nil {
return 0
}
return getMax(sum(root.Left), sum(root.Right)) + findTilt(root.Left) + findTilt(root.Right)
}
func sum(root *TreeNode) int {
if root == nil {
return 0
}
return root.Val + sum(root.Left) + sum(root.Right)
}
func getMax(a, b int) int {
if a > b {
return a - b
}
return b - a
}