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;
    }
};
相关推荐
酉鬼女又兒3 分钟前
SQL23 统计每个学校各难度的用户平均刷题数
数据库·sql·算法
爱学习的阿磊9 分钟前
模板代码跨编译器兼容
开发语言·c++·算法
毕设源码-钟学长11 分钟前
【开题答辩全过程】以 基于协同过滤推荐算法的小说漫画网站设计与实现为例,包含答辩的问题和答案
算法·机器学习·推荐算法
带鱼吃猫13 分钟前
C++STL:从 0 到 1 手写 C++ string以及高频易错点复盘
开发语言·c++
u01092727114 分钟前
代码覆盖率工具实战
开发语言·c++·算法
懈尘20 分钟前
深入理解Java的HashMap扩容机制
java·开发语言·数据结构
We་ct25 分钟前
LeetCode 73. 矩阵置零:原地算法实现与优化解析
前端·算法·leetcode·矩阵·typescript
天赐学c语言25 分钟前
2.1 - 反转字符串中的单词 && 每个进程的内存里包含什么
c++·算法·leecode
程序员泠零澪回家种桔子27 分钟前
OpenManus开源自主规划智能体解析
人工智能·后端·算法
请注意这个女生叫小美30 分钟前
C语言 实例20 25
c语言·开发语言·算法