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;
    }
};
相关推荐
geats人山人海13 分钟前
数据结构第六章c语言 树的存储下二叉树的概念和存储
c语言·数据结构·算法
迷途之人不知返1 小时前
lambda表达式
c++
jarvisuni1 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
@三十一Y1 小时前
C++:红黑树的实现
开发语言·c++
kobesdu1 小时前
流形上的优化:SO(3)与SE(3)的广义加减法在FAST-LIO中如何简化状态估计
人工智能·算法·fastlio
_wyt0011 小时前
拓扑排序:有向无环图的排队艺术
c++·拓扑排序·队列
皓月斯语1 小时前
B2118 验证子串
c++·题解
白狐_7982 小时前
408 数据结构算法题 01:线性表暴力求解保分指南
java·数据结构·算法
乐观勇敢坚强的老彭2 小时前
C++信奥:开关门、开关灯问题
开发语言·c++·算法
冻柠檬飞冰走茶2 小时前
PTA基础编程题目集 7-31 字符串循环左移(C语言实现)
c语言·开发语言·数据结构·算法