跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客我的书AI学习GitHub 精选镜像AI 生图工具UI配色美学关于
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
C算法

LeetCode 965. Univalued Binary Tree C 语言解法

LeetCode 第 965 题“单值二叉树”的解决方案。题目要求判断二叉树中所有节点的值是否相同。通过深度优先搜索(DFS)递归遍历,比较每个节点值与根节点值是否一致。若发现不同则返回 false,否则返回 true。提供了 C 语言的完整实现代码及复杂度分析。

DataScient发布于 2026/3/28更新于 2026/9/461 浏览
LeetCode 965. Univalued Binary Tree C 语言解法

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

示例 1 输入结构

Input: root = [1,1,1,1,1,null,1]
Output: true

示例 2

示例 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)  ;
     dfs(root->left, target) && dfs(root->right, target);
}

  {
     dfs(root, root->val);
}
return
false
return
bool
isUnivalTree
(struct TreeNode* root)
return

目录

  1. 965. Univalued Binary Tree
  2. 示例 1
  3. 示例 2
  4. 约束条件
  5. 解题思路
  6. 代码实现

更多推荐文章

查看全部
  • OpenAI 发布 GPT-5.3 Instant:幻觉率降低与 2026 全球 AI 模型排行
  • 12 篇必读的大模型前沿论文
  • AI 创新孵化:视频社区作为产品试验场的价值分析
  • 二分查找专题:山峰数组的峰顶索引与寻找峰值
  • Lancet 轻量级 Android AOP 框架官方文档
  • 二叉树算法实战:美国血统重建与深度宽度计算
  • GO 谷歌安装器:一键安装 Google 三件套
  • C++ 手写 JSON 与 HTTP 协议实现 Web 计算器服务器
  • SpringAI 深入解析 RAG 检索增强工作流程与调优
  • 在 IDEA 和 WebStorm 里切换 Git 分支的几种方式
  • Git 在 Windows 上的安装与配置详解
  • GitHub Codespaces 部署 OpenClaw 个人智能体实战指南
  • 大语言模型与图结构融合:推荐系统新兴范式
  • Mintlify AI 自动化文档生成工具实操指南
  • Spring AI 调用大模型的几种方案实践
  • OpenCode 开源 AI 编程助手使用指南
  • AI 支持的临床医学工作、论文撰写与机器学习建模实践
  • 电商产品 AI 绘画提示词撰写指南
  • Java 大数据在智能家居环境监测与智能调节中的应用
  • Java 不可变集合详解:List、Set 与 Map 的正确使用

相关免费在线工具

  • 加密/解密文本

    使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online

  • Gemini 图片去水印

    基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online