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;
    }
};
相关推荐
QQ12958455041 小时前
ThingsBoard部件数据结构解析
数据结构·数据库·物联网·iot
chian-ocean1 小时前
双向链表的“链”与“殇”——Rust LinkedList 的深度剖析、实战与再思考
数据结构·链表·rust
小圆5311 小时前
java-learn(9):常见算法,collection框架
java·开发语言·算法
无敌最俊朗@1 小时前
视频时间基 (time_base) 详解:时间的“刻度单位”
c++
岑梓铭1 小时前
《考研408数据结构》第七章(6.1~6.3图的概念、存储方式、深/广度遍历)复习笔记
数据结构·笔记·考研·算法·图论·408·ds
脏脏a2 小时前
【C++ 入门】:引用、内联函数与 C++11 新特性(auto、范围 for、nullptr)全解析
开发语言·c++
AA陈超2 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-28 构建属性菜单小部件控制器
c++·游戏·ue5·游戏引擎·虚幻
恒者走天下2 小时前
cpp / c++零基础就业学习一站式学习平台
开发语言·c++·学习
qq_433554542 小时前
C++ 单调栈
数据结构·c++·算法