From 10e2ef248d954c2422a48dd194d3f0266abeb8fa Mon Sep 17 00:00:00 2001 From: ductnn Date: Tue, 12 Dec 2023 20:00:21 +0700 Subject: [PATCH] add sol --- leetcode/563.BinaryTreeTilt/binaryTreeTilt.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 leetcode/563.BinaryTreeTilt/binaryTreeTilt.go diff --git a/leetcode/563.BinaryTreeTilt/binaryTreeTilt.go b/leetcode/563.BinaryTreeTilt/binaryTreeTilt.go new file mode 100644 index 0000000..13a9255 --- /dev/null +++ b/leetcode/563.BinaryTreeTilt/binaryTreeTilt.go @@ -0,0 +1,40 @@ +package main + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func findTilt(root *TreeNode) int { + result := 0 + dfs(root, &result) + return result +} + +func dfs(root *TreeNode, result *int) int { + if root == nil { + return 0 + } + left, right := dfs(root.Left, result), dfs(root.Right, result) + *result += abs(left - right) + return root.Val + right + left +} + +func abs(a int) int { + if a > 0 { + return a + } + return -a +} + +func main() {}