965. Univalued Binary Tree LeetCode Solution
In this guide, you will get 965. Univalued Binary Tree LeetCode Solution with the best time and space complexity. The solution to Univalued Binary Tree problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Univalued Binary Tree solution in C++
- Univalued Binary Tree solution in Java
- Univalued Binary Tree solution in Python
- Additional Resources

Problem Statement of Univalued Binary Tree
A binary tree is uni-valued if every node in the tree has the same value.
Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
Constraints:
The number of nodes in the tree is in the range [1, 100].
0 <= Node.val < 100
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(h)
965. Univalued Binary Tree LeetCode Solution in C++
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if (root == nullptr)
return true;
if (root->left != nullptr && root->left->val != root->val)
return false;
if (root->right != nullptr && root->right->val != root->val)
return false;
return isUnivalTree(root->left) && isUnivalTree(root->right);
}
};
/* code provided by PROGIEZ */
965. Univalued Binary Tree LeetCode Solution in Java
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null)
return true;
if (root.left != null && root.left.val != root.val)
return false;
if (root.right != null && root.right.val != root.val)
return false;
return isUnivalTree(root.left) && isUnivalTree(root.right);
}
}
// code provided by PROGIEZ
965. Univalued Binary Tree LeetCode Solution in Python
class Solution:
def isUnivalTree(self, root: TreeNode | None) -> bool:
if not root:
return True
if root.left and root.left.val != root.val:
return False
if root.right and root.right.val != root.val:
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.