题解 | #奶牛的居住区域#
奶牛的居住区域
https://www.nowcoder.com/practice/9265378f210b4ed5939424152f832221
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 # @return bool布尔型 # class Solution: def cowLivingArea(self, root: TreeNode) -> bool: # write code here if not root: return True l1, l2 = [], [] def dfs(root: TreeNode, depth: int, red_nums: int, black_fa: bool) -> None: if not root.left and not root.right: l1.append(depth) l2.append(depth - red_nums) return elif root.left and root.right: if black_fa: dfs(root.left, depth + 1, red_nums + 1, False) dfs(root.right, depth + 1, red_nums + 1, False) else: dfs(root.left, depth + 1, red_nums, True) dfs(root.right, depth + 1, red_nums, True) elif root.left: dfs(root.left, depth + 1, red_nums, True) elif root.right: dfs(root.right, depth + 1, red_nums, True) return dfs(root, 1, 0, False) if max(l2) > min(l1): return False else: return True