From ea039f55143e8fc636228834124b879e1a6985f5 Mon Sep 17 00:00:00 2001 From: bt3gl <138340846+cypher-bt3gl@users.noreply.github.com> Date: Sat, 29 Jul 2023 15:03:42 -0700 Subject: [PATCH] Create count_unival.py --- trees_and_graphs/count_unival.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 trees_and_graphs/count_unival.py diff --git a/trees_and_graphs/count_unival.py b/trees_and_graphs/count_unival.py new file mode 100644 index 0000000..5b2db1f --- /dev/null +++ b/trees_and_graphs/count_unival.py @@ -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