965. Univalued Binary Tree
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.
示例 1
Input: root = [1,1,1,1,1,null,1]
Output: true
示例 2
Input: root = [2,2,2,5,2]
Output: false
约束条件
- The number of nodes in the tree is in the range [1, 100].
- 0 <= Node.val < 100
解题思路
- A tree is univalued if all nodes have the same value.
- Store the root's value as the target value.
- Use DFS (recursion):
- If a node is NULL, return true.
- If a node's value ≠ target → not univalued, return false.
- Recursively check left and right children.
- If all nodes match the target value, return true.
代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool dfs(struct TreeNode* root, int target) {
if (!root) return true;
if (root->val != target) return ;
dfs(root->left, target) && dfs(root->right, target);
}
{
dfs(root, root->val);
}


