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;
    }
};
相关推荐
人道领域5 分钟前
【LeetCode刷题日记】47.全排列Ⅱ
java·开发语言·算法·leetcode
漂流瓶jz7 分钟前
UVA-1606 两亲性分子 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·向量·aoapc·算法竞赛入门经典·atan2·浮点
Navigator_Z9 分钟前
LeetCode //C - 1095. Find in Mountain Array
c语言·算法·leetcode
不会就选b37 分钟前
算法日常・每日刷题--<二分查找>1
算法
Chen_harmony40 分钟前
二、顺序表
数据结构
「維他檸檬茶」42 分钟前
大模型算法学习2026.6.13
学习·算法
叫我:松哥1 小时前
基于Python的共享单车租赁数据分析与预测系统,技术栈flask+boostrap+随机森林+XGBoost
人工智能·python·深度学习·算法·随机森林·数据分析·flask
磊 子1 小时前
C++设计模式
javascript·c++·设计模式
BAGAE1 小时前
星链卫星数据获取:从太空安全到实时通信的技术革命
网络·数据结构·数据库·算法·云计算·hbase
happymaker06261 小时前
LeetCodeHor100——438.找到字符串中所有的字母异位词
算法