Univalued Binary Tree

DFS verifying every node's value matches the root's.

Easy
Time O(n) Space O(h)
LeetCode
2 min read
tree dfs

Problem#

Return whether every node in the tree has the same value.

Examples#

  • [1,1,1,1,1,null,1]true
  • [2,2,2,5,2]false

Constraints#

  • The number of nodes is in [1, 100]. 0 <= Node.val < 100.

Approach#

DFS comparing each node’s value against the root’s. Short-circuit on first mismatch.

Solution#

Univalued Binary Tree
class Solution {
public:
bool isUnivalTree(TreeNode* root) {
int v = root->val;
function<bool(TreeNode*)> dfs = [&](TreeNode* u) {
if (!u) return true;
if (u->val != v) return false;
return dfs(u->left) && dfs(u->right);
};
return dfs(root);
}
};

Editorial#

Comparing against the root rather than the parent is equivalent (transitivity), and avoids passing extra state. The early return on mismatch keeps the walk short for negative inputs.

Complexity#

  • Time: O(n).
  • Space: O(h).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.