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;
    }
};
相关推荐
大闲在人13 小时前
C、C++区别还是蛮大的
c语言·开发语言·c++
追随者永远是胜利者14 小时前
(LeetCode-Hot100)20. 有效的括号
java·算法·leetcode·职场和发展·go
掘根15 小时前
【C++STL】平衡二叉树(AVL树)
开发语言·数据结构·c++
瓦特what?15 小时前
快 速 排 序
数据结构·算法·排序算法
niuniudengdeng15 小时前
基于时序上下文编码的端到端无文本依赖语音分词模型
人工智能·数学·算法·概率论
hetao173383715 小时前
2026-02-13~16 hetao1733837 的刷题记录
c++·算法
浅念-16 小时前
C++ string类
开发语言·c++·经验分享·笔记·学习
寻星探路17 小时前
【前端基础】HTML + CSS + JavaScript 快速入门(三):JS 与 jQuery 实战
java·前端·javascript·css·c++·ai·html
你的冰西瓜17 小时前
2026春晚魔术揭秘——变魔法为物理
算法