Create count_unival.py

This commit is contained in:
bt3gl 2023-07-29 15:03:42 -07:00 committed by GitHub
parent bb72bab679
commit ea039f5514
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,30 @@
'''
Given the root of a binary tree, return the number of uni-value subtrees.
A uni-value subtree means all nodes of the subtree have the same value.
'''
def count_unival(root: Optional[TreeNode]) -> int:
global count = 0
def dfs(node):
if not node:
return True
is_uni_left = dfs(node.left)
is_uni_right = dfs(node.right)
if is_uni_left and is_uni_right:
if node.left and node.left.val != node.val:
return False
if node.right and node.right.val != node.val:
return False
self.count += 1
return True
return False
dfs(root)
return count