Thanks to visit codestin.com Credit goes to github.com
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c8972d3 commit f67efa0Copy full SHA for f67efa0
979.distribute-coins-in-binary-tree.go
@@ -0,0 +1,38 @@
1
+/*
2
+ * @lc app=leetcode id=979 lang=golang
3
+ *
4
+ * [979] Distribute Coins in Binary Tree
5
+ */
6
+/**
7
+ * Definition for a binary tree node.
8
+ * type TreeNode struct {
9
+ * Val int
10
+ * Left *TreeNode
11
+ * Right *TreeNode
12
+ * }
13
14
+// (0 ms)
15
+func distributeCoins(root *TreeNode) int {
16
+ rtn := 0
17
+ moves(root, &rtn)
18
+ return rtn
19
+}
20
+
21
+// root树平衡需要从外面获取的节点数,可能正,可能负
22
+func moves(root *TreeNode, ans *int) int {
23
+ if root == nil {
24
+ return 0
25
+ }
26
27
+ l := moves(root.Left, ans)
28
+ r := moves(root.Right, ans)
29
+ *ans += abs(l) + abs(r) // 移动的数目和root.Val 没有关系
30
+ return root.Val - 1 + l + r
31
32
33
+func abs(a int) int {
34
+ if a < 0 {
35
+ return -a
36
37
+ return a
38
0 commit comments