# 965.Univalued Binary Tree

**965.Univalued Binary Tree**

难度:Easy

> 如果二叉树每个节点都具有相同的值，那么该二叉树就是单值二叉树。 只有给定的树是单值二叉树时，才返回 true；否则返回 false。

示例 1： ![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/29/screen-shot-2018-12-25-at-50104-pm.png) 输入：\[1,1,1,1,1,null,1] 输出：true 示例 2：

![](https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/29/screen-shot-2018-12-25-at-50050-pm.png) 输入：\[2,2,2,5,2] 输出：false

提示： 给定树的节点数范围是 \[1, 100]。 每个节点的值都是整数，范围为 \[0, 99] 。

代码如下：

```
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if(!root) return true;
        if(!root->left && !root->right) return true;
        if(root->left && root->val!=root->left->val) return false;
        if(root->right && root->val !=root->right->val) return false;
        return isUnivalTree(root->left) && isUnivalTree(root->right);
        
    }
};
```

> 执行用时 : 16 ms, 在Univalued Binary Tree的C++提交中击败了4.04% 的用户 内存消耗 : 11.3 MB, 在Univalued Binary Tree的C++提交中击败了100.00% 的用户


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/965.univalued_binary_tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
