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;
    }
};
相关推荐
逆小舟14 分钟前
【Linux】人事档案——用户及组管理
linux·c++
风中的微尘5 小时前
39.网络流入门
开发语言·网络·c++·算法
混分巨兽龙某某6 小时前
基于Qt Creator的Serial Port串口调试助手项目(代码开源)
c++·qt creator·串口助手·serial port
西红柿维生素6 小时前
JVM相关总结
java·jvm·算法
小冯记录编程6 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
C_Liu_6 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan7 小时前
【C++】类和对象1
java·开发语言·c++
阿昭L7 小时前
MFC仿真
c++·mfc
ChillJavaGuy7 小时前
常见限流算法详解与对比
java·算法·限流算法
散1127 小时前
01数据结构-01背包问题
数据结构