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;
    }
};
相关推荐
Molesidy16 小时前
【VSCode】【Clangd】Win下的基于LLVM/Clangd+Clangd插件+MINGW+CMake的VSCode配置C/C++开发环境的详细教程
c++·ide·vscode·clangd·llvm
报错小能手17 小时前
刷题日常 5 二叉树最大深度
算法
码银17 小时前
【数据结构】顺序表
java·开发语言·数据结构
Greedy Alg17 小时前
LeetCode 84. 柱状图中最大的矩形(困难)
算法
Mr_WangAndy17 小时前
C++_chapter13_C++并发与多线程_多线程概念,死锁,unique_lock(),lock_guard()使用
c++·lock·死锁·并发与多线程·unlock·lock_guard·unique_lock
im_AMBER17 小时前
Leetcode 52
笔记·学习·算法·leetcode
小欣加油17 小时前
leetcode 946 验证栈序列
c++·算法·leetcode·职场和发展
神仙别闹17 小时前
基于QT(C++) 实现哈夫曼压缩(多线程)
java·c++·qt
包饭厅咸鱼18 小时前
PaddleOCR----制作数据集,模型训练,验证 QT部署(未完成)
算法