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;
    }
};
相关推荐
多弗朗皮卡丘4 分钟前
C++特殊类设计
开发语言·c++·设计模式
志起计算机编程31 分钟前
Clickhouse的几个关键优势
算法
重生之小比特35 分钟前
【算法拾光 7】双指针|两数之和 II - 输入有序数组 + 三数之和
算法
Hello World . .39 分钟前
【嵌入式学习笔记 Day 1】
linux·数据结构·笔记
H.莓飛44 分钟前
【数据结构】归并与外排序
linux·服务器·c语言·开发语言·数据结构·visual studio
文丑颜不良啊1 小时前
LeetCode851~875题目解析
java·leetcode
Navigator_Z1 小时前
LeetCode //C - 1304. Find N Unique Integers Sum up to Zero
c语言·算法·leetcode
Yyyyyy~1 小时前
【C++】String
c++
BK贝壳10 小时前
bool-hybrid-array 落盘我只认 .bha:用 Create_BHA / Ask_BHA 做布尔数组序列化
数据结构·python·numpy·1024程序员节