LeetCode968. 监控二叉树
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/binary-tree-cameras/description/
代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minCameraCover(self, root: Optional[TreeNode]) -> int:
result = [0]
if self.traversal(root, result) == 0:
result[0] += 1
return result[0]
def traversal(self, cur, result):
if not cur:
return 2
left = self.traversal(cur.left, result)
right = self.traversal(cur.right, result)
if left == 2 and right == 2:
return 0
if left == 0 or right == 0:
result[0] += 1
return 1
if left == 1 or right == 1:
return 2