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;
    }
};
相关推荐
小怡同学..20 分钟前
c++系列之智能指针的使用
开发语言·c++
金融小师妹1 小时前
基于LSTM-GARCH混合模型的“获利了结”量化解析:黄金单日1.27%跌幅的技术性归因
大数据·人工智能·算法
不良手残2 小时前
Java实现10大经典排序算法
数据结构·算法·排序算法
是紫焅呢2 小时前
I排序算法.go
开发语言·后端·算法·golang·排序算法·学习方法·visual studio code
mxpan2 小时前
C++ 单例模式一种实现方式
c++·设计模式
辉辉还没睡2 小时前
Lora训练
人工智能·算法·机器学习
whoarethenext3 小时前
使用 C++/OpenCV 计算图像特征并用 Faiss 进行相似细节搜索
c++·opencv·faiss
日月星宿~3 小时前
【redis】数据结构及操作命令
数据结构·数据库·redis
lyx 弈心3 小时前
数据结构 双向链表与双向循环链表 6.17
数据结构·链表
only-lucky3 小时前
C++设计模式
java·c++·设计模式