Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check all values in the tree are same or not in Python
Suppose we have a binary tree, we have to check whether all nodes in the tree have the same values or not. This is a common tree traversal problem that can be solved using recursive depth-first search.
So, if the input is like ?
then the output will be True
Algorithm
To solve this, we will follow these steps ?
Define a function
solve(). This will take root, and val-
if root is null, then
return True
-
if val is not defined, then
val := value of root
return true when value of root is same as val and solve(left of root, val) and solve(right of root, val) are also true
Implementation
Let us see the following implementation to get better understanding ?
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def solve(self, root, val=None):
if not root:
return True
if val is None:
val = root.val
return (root.val == val and
self.solve(root.left, val) and
self.solve(root.right, val))
# Create the tree
ob = Solution()
root = TreeNode(5)
root.left = TreeNode(5)
root.right = TreeNode(5)
root.left.left = TreeNode(5)
root.left.right = TreeNode(5)
print(ob.solve(root))
True
How It Works
The algorithm uses recursive traversal:
Base case: If we reach a null node, return True (empty subtree is valid)
Initial value: On first call, set val to root's value
Recursive check: Current node must equal val AND both subtrees must be uniform
Testing with Different Values
Let's test with a tree that has different values ?
# Test with mixed values root2 = TreeNode(5) root2.left = TreeNode(5) root2.right = TreeNode(3) # Different value ob = Solution() print(ob.solve(root2))
False
Conclusion
This recursive solution efficiently checks if all nodes in a binary tree have the same value. The algorithm has O(n) time complexity and O(h) space complexity where h is the tree height.
