965. Univalued Binary Tree
1. Description
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.
2. Example
Example 1:
Input: root = [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: root = [2,2,2,5,2]
Output: false
3. Constraints
- The number of nodes in the tree is in the range [1, 100].
- 0 <= Node.val < 100
4. Solutions
Depth-First Search
n is the number of nodes in root
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
bool isUnivalTree(TreeNode *root) {
return root == nullptr ||
(isUnivalTree(root->left) && isUnivalTree(root->right) &&
(root->left != nullptr ? root->val == root->left->val : true) &&
(root->right != nullptr ? root->val == root->right->val : true));
}
};