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 分钟前
【Leetcode】 接雨水
java·算法·leetcode
星恒随风5 分钟前
C++ 类和对象入门(一):从 class、访问限定符到 this 指针
开发语言·c++·笔记·学习·状态模式
赵民勇7 分钟前
如何查看一个二进制程序是否设置了rpath或runpath?
linux·c++
Brilliantwxx9 分钟前
【C++】 哈希表 unordered_map 与 unordered_set(底层原理 + 线性哈希表代码实现)
开发语言·c++·散列表
南境十里·墨染春水20 分钟前
讲讲移动语义
算法
西凉的悲伤28 分钟前
Guava类库——Range连续区间
java·算法·guava
菜菜的顾清寒29 分钟前
力扣HOT(100)54多维动态规划-最长公共子序列
算法·leetcode·动态规划
ouliten30 分钟前
C++笔记:C++20风格线程池
c++·笔记·c++20
随意起个昵称34 分钟前
线性dp-LIS题目3(合唱队形)
算法
weixin_4671822834 分钟前
Arduino进阶二|自定义类库保姆级教程(从零手写属于自己的传感器类库+完整源码)
c语言·c++·单片机·嵌入式硬件·arduino·c++面向对象·diy库文件