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.
1bool isUnival(TreeNode* root, int value) {
2 if (root == NULL) return true;
3 if (root->val != value) return false;
4 return isUnival(root->left, value) && isUnival(root->right, value);
5}
6bool isUnivalTree(TreeNode* root) {
7 return isUnival(root, root->val);
8}
The function isUnival()
checks recursively whether the node value equals the desired value (root->val
). This involves checking the left and right subtrees. If any node value doesn't match, it returns false.
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.
1var
The JavaScript solution uses an array as a dynamic queue. Nodes are processed in a FIFO manner, checking values as they are dequeued and ensuring tree-wide value uniformity.