LeetCode 250. [Python] Count Univalue Subtrees
原题链接
中等
作者:
徐辰潇
,
2021-03-06 05:13:57
,
所有人可见
,
阅读 495
# 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
#Just check the whether the left and right subtrue are uni-value or not
#If left and right subtruee are uni-vale, then check whether the node value and the value of two subtrees are the same
class Solution:
def countUnivalSubtrees(self, root: TreeNode) -> int:
self.res = 0
self.dfs(root)
return self.res
def dfs(self, root):
if not root:
return [True, None]
left, left_val = self.dfs(root.left)
right, right_val = self.dfs(root.right)
Bool = False
if left and right:
if left_val is None and right_val is None:
Bool = True
elif left_val is None:
Bool = (root.val == right_val)
elif right_val is None:
Bool = (root.val == left_val)
else:
Bool = (root.val == left_val) and (root.val == right_val)
if Bool:
self.res += 1
return [Bool, root.val]