LeetCode 965: Univalued Binary Tree Solution
Master LeetCode problem 965 (Univalued Binary Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
965. Univalued Binary Tree
Problem Explanation
Explanation:
To determine if a binary tree is univalued, we need to check if all nodes in the tree have the same value as the root node. We can perform a depth-first search (DFS) traversal of the tree and compare each node's value with the value of the root node. If any node's value is different, we return false. If all nodes have the same value, we return true.
Algorithm:
- Initialize a global variable
univalto true. - Implement a depth-first search function
isUnivalTreeDFSthat takes a node and a value as parameters. - In the
isUnivalTreeDFSfunction: a. If the node is null, return true. b. If the node's value is not equal to the given value, setunivalto false. c. Recursively call the function on the left and right children of the node. - Call the
isUnivalTreeDFSfunction with the root node's value as the initial value. - Return the value of
unival.
Time Complexity: O(n), where n is the number of nodes in the binary tree. Space Complexity: O(h), where h is the height of the binary tree.
:
Solution Code
class Solution {
boolean unival = true;
public boolean isUnivalTree(TreeNode root) {
if (root == null) {
return true;
}
isUnivalTreeDFS(root, root.val);
return unival;
}
private void isUnivalTreeDFS(TreeNode node, int val) {
if (node == null) {
return;
}
if (node.val != val) {
unival = false;
}
isUnivalTreeDFS(node.left, val);
isUnivalTreeDFS(node.right, val);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 965 (Univalued Binary Tree)?
This page provides optimized solutions for LeetCode problem 965 (Univalued Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 965 (Univalued Binary Tree)?
The time complexity for LeetCode 965 (Univalued Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 965 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 965 in Java, C++, or Python.