mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update bt_count_unival.py
This commit is contained in:
parent
b61c58b158
commit
94de93780a
@ -2,29 +2,20 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
'''
|
|
||||||
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:
|
|
||||||
|
def count_unival(root) -> int:
|
||||||
|
|
||||||
global count = 0
|
global count = 0
|
||||||
|
|
||||||
def dfs(node):
|
def dfs(node):
|
||||||
|
if node is None:
|
||||||
if not node:
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
is_uni_left = dfs(node.left)
|
if dfs(node.left) and dfs(node.right):
|
||||||
is_uni_right = dfs(node.right)
|
if (node.left and node.left.val != node.val) or \
|
||||||
|
(node.right and node.right.val != node.val):
|
||||||
if is_uni_left and is_uni_right:
|
return False
|
||||||
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
|
self.count += 1
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user