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 分钟前
ROS2 机器人软件系统
linux·c++·python·ubuntu·vmware·ros2·机器人软件开发
从零开始的代码生活_24 分钟前
NAT、代理服务与内网穿透详解
linux·服务器·网络·c++·http·智能路由器
aaaameliaaa27 分钟前
进制练习题【找出只出现一次的数字、交换两个变量(不创建临时变量)、统计二进制中1的个数、打印整数二进制的奇数位和偶数位、求两个数二进制中不同位的个数】
c语言·数据结构·笔记·算法
charlie1145141911 小时前
Cinux: 加载第一个内核:从 bootloader 跳进 C++
linux·开发语言·c++·嵌入式
QiLinkOS2 小时前
第三视觉理解徐玉生与他的商业活动(28)
大数据·c++·人工智能·算法·开源协议
星夜夏空992 小时前
C++学习(2) —— 类与对象基础
开发语言·c++·学习
wabs6663 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月3 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
Robot_Nav3 小时前
MPPI 局部规划器实验设计讲解
人工智能·算法·mppi
mingo_敏4 小时前
Mean-Teacher 均值教师自训练框架详解
算法·均值算法