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;
    }
};
相关推荐
程序员老陆14 小时前
C++ 将亡值(xvalue)深度解析:从表达式分类到参数传递陷阱
c++·程序设计
嘎嘎风14 小时前
MiniMind 学习笔记之 02 字是怎么变成数字的?
算法
QAQmmttyyy14 小时前
ChatFly 开发实录 ⑧|一个 VAD 的自我修养
算法
Logic10114 小时前
关于汉诺塔问题的分析
c语言·算法·递归·函数·解题思路·递归函数·汉诺塔问题
维克兜率天14 小时前
【维克】配对交易的季节性:哪些品种适合长拿?
android·开发语言·笔记·python·算法·kotlin·量化
沫璃染墨15 小时前
《Qt从零入门系列(十二):Qt文件操作详解——从QFile读写到QFileInfo与记事本实战》
开发语言·网络·c++·qt·交互·信号处理·文件
青少儿编程课堂15 小时前
树上启发式合并详解:子树颜色众数统计与复杂度拆解
c++·python·算法·bfs·信息学竞赛
hahaha601615 小时前
完美反射法--白平衡算法
人工智能·算法
路弥行至15 小时前
【Head First 设计模式】第 2 章:观察者模式 —— 用现代 C++ 重新解读“交互对象的松耦合
c++·经验分享·笔记·观察者模式·设计模式·入门教程·headfirst
YYYing.15 小时前
【设计模式系列 (九) 】装饰器模式
c++·后端·设计模式·装饰器模式·c/c++