LeetCode965. 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.

Example 1:

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

Output: true

Example 2:

Input: root = [2,2,2,5,2]

Output: false

Constraints:

The number of nodes in the tree is in the range [1, 100].

0 <= Node.val < 100

二、题解

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pre;
    bool isUnivalTree(TreeNode* root) {
        if(root == nullptr) return true;
        if(pre != nullptr){
            if(pre->val != root->val) return false;
        }
        pre = root;
        bool leftUni = isUnivalTree(root->left);
        bool rightUni = isUnivalTree(root->right);
        return leftUni && rightUni;
    }
};
相关推荐
CoovallyAIHub8 分钟前
ICLR 2026 | MRAD:不拟合直接查表,零样本工业缺陷检测新范式,16 数据集均值最优
深度学习·算法·计算机视觉
摆烂小白敲代码8 分钟前
【数据结构与算法】汉诺塔问题(C++)
c语言·开发语言·数据结构·c++·算法·hanoi·汉诺塔问题
Trouvaille ~14 分钟前
【递归、搜索与回溯】专题(八):记忆化搜索——从暴力递归到动态规划的桥梁
c++·算法·leetcode·青少年编程·面试·蓝桥杯·动态规划
Sincerelyplz18 分钟前
【LeetForge】我用AI写了一个 LeetCode 刷题自动追踪工具,从此告别手动打卡
leetcode·cursor
Pu_Nine_922 分钟前
深入理解 ES6 Map 数据结构:从理论到实战应用
前端·javascript·数据结构·es6
刚入坑的新人编程32 分钟前
C++qt(3)-按钮类控件
开发语言·c++·qt
乐观勇敢坚强的老彭34 分钟前
本周C++编程课笔记:for循环练习
java·c++·笔记
飞Link37 分钟前
降维打击聚类难题:高斯混合模型 (GMM) 深度解析与实战
人工智能·算法·机器学习·数据挖掘·聚类
沐苏瑶39 分钟前
Java数据结构-LinkedList与链表
java·数据结构·链表