---
# System prepended metadata

title: Univalued Binary Tree
tags: [Breadth-First Search, Depth-First Search, Binary Tree, LeetCode]

---

---
description: Today 1 leet , tomorrow 頂天leet地
image: https://leetcode.com/static/images/LeetCode_Sharing.png
---
# Univalued Binary Tree
[題目網址<i class="fa fa-link"></i>](https://leetcode.com/problems/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.
:::spoiler **Example 1**

> **Input:** [1,1,1,1,1,null,1]
> **Output:** true
:::

:::spoiler **Example 2**
> **Input:** [2,2,2,5,2]
> **Output:** false
:::


## 解題思維
以遞迴遍歷有無不一樣的val


## 程式碼

```cpp=!
class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if(root==NULL||(root->right==NULL&&root->left==NULL))
            return 1;
        if( (root->right!=NULL&&root->right->val!=root->val)
        ||(root->left!=NULL&&root->left->val!=root->val) )
            return 0;
        return isUnivalTree(root->right)&&isUnivalTree(root->left);
    }
};
```





###### tags: `LeetCode` `Depth-First Search` `Breadth-First Search` `Binary Tree`