Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f67efa0

Browse files
author
侯利朋
committed
.\979.distribute-coins-in-binary-tree ok
1 parent c8972d3 commit f67efa0

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)