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;
    }
};
相关推荐
香蕉卜拿拿拿7 分钟前
软件解耦与扩展的利器:基于C++与C#的插件式开发实践
c++
aigcapi12 分钟前
RAG 系统的黑盒测试:从算法对齐视角解析 GEO 优化的技术指标体系
大数据·人工智能·算法
苏宸啊1 小时前
链式二叉树基操代码实现&OJ题目
数据结构
风筝在晴天搁浅1 小时前
hot100 25.K个一组翻转链表
数据结构·链表
CoderCodingNo1 小时前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
柯慕灵1 小时前
7大推荐系统/算法框架对比
算法·推荐算法
adam-liu2 小时前
Fun Audio Chat 论文+项目调研
算法·语音端到端·fun-audio-chat
小十一再加一2 小时前
【初阶数据结构】栈和队列
数据结构
栀秋6662 小时前
你会先找行还是直接拍平?两种二分策略你Pick哪个?
前端·javascript·算法
如果你想拥有什么先让自己配得上拥有2 小时前
数学思想和数学思维分别都有什么?
线性代数·算法·机器学习