题解 | #奶牛的居住区域#

奶牛的居住区域

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

全部评论

相关推荐

点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务