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;
    }
};
相关推荐
qq_513970444 分钟前
力扣 hot100 Day37
算法·leetcode
不見星空24 分钟前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack34 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
米饭「」36 分钟前
C++AVL树
java·开发语言·c++
☆璇1 小时前
【数据结构】栈和队列
c语言·数据结构
心愿许得无限大1 小时前
Qt 常用界面组件
开发语言·c++·qt
GiraKoo1 小时前
【GiraKoo】C++17的新特性
c++
Rockson1 小时前
C++如何查询实时贵金属行情
c++·api
shenyan~1 小时前
关于 c、c#、c++ 三者区别
开发语言·c++
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法