0563. Binary Tree Tilt

# 563. Binary Tree Tilt#

## 题目 #

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

Example:

``````Input:
1
/   \
2     3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
``````

Note:

1. The sum of node values in any subtree won’t exceed the range of 32-bit integer.
2. All the tilt values won’t exceed the range of 32-bit integer.

## 题目大意 #

1. 任何子树的结点的和不会超过32位整数的范围。
2. 坡度的值不会超过32位整数的范围。

## 解题思路 #

• 给出一棵树，计算每个节点的“倾斜度”累加和。“倾斜度”的定义是：左子树和右子树的节点值差值的绝对值。
• 这一题虽然是简单题，但是如果对题目中的“倾斜度”理解的不对，这一题就会出错。“倾斜度”计算的是左子树所有节点的值总和，和，右子树所有节点的值总和的差值。并不是只针对一个节点的左节点值和右节点值的差值。这一点明白以后，这一题就是简单题了。

## 代码 #

``````
package leetcode

import "math"

/**
* 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
}
sum := 0
findTiltDFS(root, &sum)
return sum
}

func findTiltDFS(root *TreeNode, sum *int) int {
if root == nil {
return 0
}
left := findTiltDFS(root.Left, sum)
right := findTiltDFS(root.Right, sum)
*sum += int(math.Abs(float64(left) - float64(right)))
return root.Val + left + right
}

``````

Sep 6, 2020