> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/965.univalued_binary_tree.md).

# 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
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
