mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
39 lines
649 B
Go
39 lines
649 B
Go
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
|
|
}
|