Sponsored
Sponsored
The recursive DFS approach involves starting from the root and checking if every node has the same value as the root node. This can be achieved by recursively checking the left and right subtrees of each node. If a node value differs from the root node's value, we return false immediately.
Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to the recursion stack.
1class Solution {
2 public boolean isUnivalTree(TreeNode root) {
3 return isUnivalTree(root, root.val);
4 }
5 private boolean isUnivalTree(TreeNode node, int val) {
6 if (node == null) return true;
7 if (node.val != val) return false;
8 return isUnivalTree(node.left, val) && isUnivalTree(node.right, val);
9 }
10}
In Java, we create a recursive helper function inside the class to perform checks, allowing us to compare each node's value with the root's value through depth-first traversal.
An iterative BFS approach uses a queue to level-order traverse the tree. We compare each node's value to the root's value. If any node differs, the function returns false.
Time Complexity: O(n), as each node is checked once.
Space Complexity: O(n), due to the queue storing at most one level of the tree.
1#include <queue>
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
int value = root->val;
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node->val != value) return false;
if (node->left != nullptr) q.push(node->left);
if (node->right != nullptr) q.push(node->right);
}
return true;
}
};
C++ utilizes the STL queue for breadth-first traversal, comparing each node to the initial value. If nodes differ, false is returned immediately.