forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
count-nodes-equal-to-sum-of-descendants.py
57 lines (50 loc) · 1.55 KB
/
count-nodes-equal-to-sum-of-descendants.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
pass
class Solution(object):
def equalToDescendants(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
def iter_dfs(node):
result = 0
stk = [(1, [node, [0]])]
while stk:
step, args = stk.pop()
if step == 1:
node, ret = args
if not node:
continue
ret1, ret2 = [0], [0]
stk.append((2, [node, ret1, ret2, ret]))
stk.append((1, [node.right, ret2]))
stk.append((1, [node.left, ret1]))
elif step == 2:
node, ret1, ret2, ret = args
if node.val == ret1[0]+ret2[0]:
result += 1
ret[0] = ret1[0]+ret2[0]+node.val
return result
return iter_dfs(root)
# Time: O(n)
# Space: O(h)
class Solution2(object):
def equalToDescendants(self, root):
"""
:type root: Optional[TreeNode]
:rtype: int
"""
def dfs(node, result):
if not node:
return 0
total = dfs(node.left, result) + dfs(node.right, result)
if node.val == total:
result[0] += 1
return total+node.val
result = [0]
dfs(root, result)
return result[0]