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 ?

5 5 5 5 5

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.

Updated on: 2026-03-25T11:46:29+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements