題目
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:
- The sum of node values in any subtree won't exceed the range of 32-bit integer.
- All the tilt values won't exceed the range of 32-bit integer.
題目大意
給定二叉樹,計算二叉樹的“傾斜值”(tilt)
二叉樹節點的傾斜值是指其左右子樹和的差的絕對值。空節點的傾斜值為0。
注意:
- 節點和不超過32位整數范圍
- 傾斜值不超過32位整數范圍
解題思路
遍歷二叉樹,求二叉樹子樹的和
累加各子樹的傾斜值,得到二叉樹的傾斜值
代碼
findTilt.go
package _563_Binary_Tree_Tilt
import "math"
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var tilt int
func subTreeSum(t *TreeNode) (sum int){
if nil == t {
return 0
}
left := subTreeSum(t.Left)
right := subTreeSum(t.Right)
tilt += int(math.Abs((float64(left) - float64(right))))
return t.Val + left + right
}
func FindTilt(root *TreeNode) int {
tilt = 0
subTreeSum(root)
return tilt
}
測試
findTilt_test.go
package _563_Binary_Tree_Tilt
import "testing"
func InitTree(index int, input []int) (t *TreeNode) {
if index > len(input) {
return nil
}
t = new(TreeNode)
t.Val = input[index - 1]
t.Left = InitTree(index*2, input)
t.Right = InitTree(index*2 + 1, input)
return t
}
func TestFindTilt(t *testing.T) {
input1 := []int{1,2,3}
var tests = []struct{
tree *TreeNode
output int
}{
{InitTree(1, input1), 1},
}
for _, test := range tests {
ret := FindTilt(test.tree)
if ret == test.output {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", test.output, ret)
}
}
}