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:
[1, 100].0 <= Node.val < 100The 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.
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.
C++
Java
Python
C#
JavaScript
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.
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.
This C solution uses an explicit queue structure to iteratively traverse nodes level-wise, checking if each has the same value as the root. Queues ensure that nodes are processed in insertion order.
C++
Java
Python
C#
JavaScript
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.
| Approach | Complexity |
|---|---|
| Recursive Depth-First Search (DFS) | Time Complexity: O(n), where n is the number of nodes in the tree, as each node is visited once. |
| Iterative Breadth-First Search (BFS) | Time Complexity: O(n), as each node is checked once. |
Symmetric Tree - Leetcode 101 - Python • NeetCodeIO • 48,748 views views
Watch 9 more video solutions →Practice Univalued Binary Tree with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor