-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
evaluate-boolean-binary-tree.py
64 lines (55 loc) · 1.64 KB
/
evaluate-boolean-binary-tree.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
58
59
60
61
62
63
64
# Time: O(n)
# Space: O(h)
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
pass
# dfs with stack
class Solution(object):
def evaluateTree(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
INF = float("inf")
OP = {
2: lambda x, y: x or y,
3: lambda x, y: x and y
}
def iter_dfs(root):
ret = [0]
stk = [(1, (root, ret))]
while stk:
step, args = stk.pop()
if step == 1:
node, ret = args
if node.left == node.right:
ret[0] = node.val
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
ret[0] = OP[node.val](ret1[0], ret2[0])
return ret[0]
return iter_dfs(root)
# Time: O(n)
# Space: O(h)
# dfs with recursion
class Solution2(object):
def evaluateTree(self, root):
"""
:type root: Optional[TreeNode]
:rtype: bool
"""
INF = float("inf")
OP = {
2: lambda x, y: x or y,
3: lambda x, y: x and y,
}
def dfs(node):
if node.left == node.right:
return node.val
return OP[node.val](dfs(node.left), dfs(node.right))
return dfs(root)