forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-tree-cameras.py
32 lines (28 loc) · 892 Bytes
/
binary-tree-cameras.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
# Time: O(n)
# Space: O(h)
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def minCameraCover(self, root):
"""
:type root: TreeNode
:rtype: int
"""
UNCOVERED, COVERED, CAMERA = range(3)
def dfs(root, result):
left = dfs(root.left, result) if root.left else COVERED
right = dfs(root.right, result) if root.right else COVERED
if left == UNCOVERED or right == UNCOVERED:
result[0] += 1
return CAMERA
if left == CAMERA or right == CAMERA:
return COVERED
return UNCOVERED
result = [0]
if dfs(root, result) == UNCOVERED:
result[0] += 1
return result[0]