Skip to content

Commit 73936b6

Browse files
authored
Create distribute-coins-in-binary-tree.py
1 parent 9f1c451 commit 73936b6

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(n)
2+
# Space: O(h)
3+
4+
# Definition for a binary tree node.
5+
class TreeNode(object):
6+
def __init__(self, x):
7+
self.val = x
8+
self.left = None
9+
self.right = None
10+
11+
12+
class Solution(object):
13+
def distributeCoins(self, root):
14+
"""
15+
:type root: TreeNode
16+
:rtype: int
17+
"""
18+
def dfs(root, result):
19+
if not root:
20+
return 0
21+
left, right = dfs(root.left, result), dfs(root.right, result)
22+
result[0] += abs(left) + abs(right)
23+
return root.val + left + right - 1
24+
25+
result = [0]
26+
dfs(root, result)
27+
return result[0]

0 commit comments

Comments
 (0)