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;
    }
};
相关推荐
岛雨QA27 分钟前
递归「Java数据结构与算法学习笔记5」
数据结构·算法
kebijuelun30 分钟前
Learning Personalized Agents from Human Feedback:用人类反馈训练可持续个性化智能体
人工智能·深度学习·算法·transformer
tod11333 分钟前
C++ 核心知识点全解析(八)
开发语言·c++·面试经验
Ljwuhe36 分钟前
C++类与对象(上)
开发语言·c++
Eloudy39 分钟前
稀疏矩阵的 CSR 格式(Compressed Sparse Row)
人工智能·算法·arch·hpc
killer_queen480440 分钟前
AI_agent(三) MCP协议(二)
c++·agent·mcp·a2a
岛雨QA44 分钟前
栈「Java数据结构与算法学习笔记4」
数据结构·算法
乐观勇敢坚强的老彭1 小时前
c++寒假营day05
开发语言·c++·算法
枫叶丹41 小时前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
重生之后端学习1 小时前
74. 搜索二维矩阵
开发语言·数据结构·算法·职场和发展·深度优先