# 965. Univalued Binary Tree

A binary tree is  univalued  if every node in the tree has the same value.

Return `true` if and only if the given tree is univalued.

Example 1:

``````Input: [1,1,1,1,1,null,1]
Output: true
``````

Example 2:

``````Input: [2,2,2,5,2]
Output: false
``````

Note:

1. The number of nodes in the given tree will be in the range `[1, 100]`.
2. Each node’s value will be an integer in the range `[0, 99]`.

``````class Solution {
public:
bool isUnivalTree(TreeNode* root) {
return helper(root, root->val);
}
bool helper(TreeNode* node, int val) {
if (!node) return true;
if (node->val != val) return false;
return helper(node->left, val) && helper(node->right, val);
}
};
``````

``````class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if (!root) return true;
if (root->left && root->left->val != root->val) return false;
if (root->right && root->right->val != root->val) return false;
return isUnivalTree(root->left) && isUnivalTree(root->right);
}
};
``````

``````class Solution {
public:
bool isUnivalTree(TreeNode* root) {
if (!root) return true;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
TreeNode* t = q.front(); q.pop();
if (t->val != root->val) return false;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
return true;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/965

Find All The Lonely Nodes

https://leetcode.com/problems/univalued-binary-tree/

https://leetcode.com/problems/univalued-binary-tree/discuss/211190/JavaC%2B%2BPython-Straight-Forward

https://leetcode.com/problems/univalued-binary-tree/discuss/252904/C%2B%2B-4-Lines-of-Code-Beats-100-Easy-to-Understand

https://leetcode.com/problems/univalued-binary-tree/discuss/211397/JavaPython-3-BFS-and-DFS-clean-codes-w-brief-analysis.

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation