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;
    }
};
相关推荐
想做小南娘,发现自己是女生喵19 分钟前
第 2 章 顺序表和 vector
java·数据结构·算法
ComputerInBook42 分钟前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
艾醒1 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
AA陈超1 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
雪碧聊技术1 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo1 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花2 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
蓝创精英团队2 小时前
VCPKG 跨平台C++ 库管理器
c++·vcpkg
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
Reart2 小时前
Leetcode 300.最长递增子序列(719)
算法