mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-05-06 08:45:11 -04:00
Rename count_unival.py to bt_count_unival.py
This commit is contained in:
parent
5b67529485
commit
0871054dd3
1 changed files with 0 additions and 0 deletions
34
trees/bt_count_unival.py
Normal file
34
trees/bt_count_unival.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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:
|
||||
|
||||
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
|
Loading…
Add table
Add a link
Reference in a new issue