规范格式

This commit is contained in:
YDZ
2020-08-07 15:50:06 +08:00
parent 854a339abc
commit 4e11f4028a
1438 changed files with 907 additions and 924 deletions

View File

@ -0,0 +1,38 @@
package leetcode
import "math"
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* 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
}

View File

@ -0,0 +1,66 @@
package leetcode
import (
"fmt"
"testing"
"github.com/halfrost/LeetCode-Go/structures"
)
type question563 struct {
para563
ans563
}
// para 是参数
// one 代表第一个参数
type para563 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans563 struct {
one int
}
func Test_Problem563(t *testing.T) {
qs := []question563{
question563{
para563{[]int{}},
ans563{0},
},
question563{
para563{[]int{1}},
ans563{0},
},
question563{
para563{[]int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}},
ans563{41},
},
question563{
para563{[]int{1, 2, 3, 4, structures.NULL, structures.NULL, 5}},
ans563{11},
},
question563{
para563{[]int{1, 2, 3, 4, structures.NULL, 5}},
ans563{11},
},
}
fmt.Printf("------------------------Leetcode Problem 563------------------------\n")
for _, q := range qs {
_, p := q.ans563, q.para563
fmt.Printf("【input】:%v ", p)
root := structures.Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", findTilt(root))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,45 @@
# [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位整数的范围。
## 解题思路
- 给出一棵树,计算每个节点的“倾斜度”累加和。“倾斜度”的定义是:左子树和右子树的节点值差值的绝对值。
- 这一题虽然是简单题,但是如果对题目中的“倾斜度”理解的不对,这一题就会出错。“倾斜度”计算的是左子树所有节点的值总和,和,右子树所有节点的值总和的差值。并不是只针对一个节点的左节点值和右节点值的差值。这一点明白以后,这一题就是简单题了。