添加内容

This commit is contained in:
YDZ
2020-08-08 09:17:26 +08:00
parent 5015cc6b7b
commit fdba30f0c4
734 changed files with 4024 additions and 2129 deletions

View File

@ -0,0 +1,83 @@
# [563. Binary Tree Tilt](https://leetcode.com/problems/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.
## 题目大意
给定一个二叉树计算整个树的坡度。一个树的节点的坡度定义即为该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。整个树的坡度就是其所有节点的坡度之和。
注意:
1. 任何子树的结点的和不会超过32位整数的范围。
2. 坡度的值不会超过32位整数的范围。
## 解题思路
- 给出一棵树,计算每个节点的“倾斜度”累加和。“倾斜度”的定义是:左子树和右子树的节点值差值的绝对值。
- 这一题虽然是简单题,但是如果对题目中的“倾斜度”理解的不对,这一题就会出错。“倾斜度”计算的是左子树所有节点的值总和,和,右子树所有节点的值总和的差值。并不是只针对一个节点的左节点值和右节点值的差值。这一点明白以后,这一题就是简单题了。
## 代码
```go
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
}
```