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;
    }
};
相关推荐
IronMurphy6 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬6 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership6 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826526 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
山甫aa7 小时前
差分数组 ----- 从零开始的数据结构
数据结构
早日退休!!!7 小时前
《数据结构选型指南》笔记
数据结构·数据库·oracle
Beginner x_u7 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
丑八怪大丑7 小时前
Java数据结构与集合源码
数据结构
c++之路8 小时前
C++信号处理
开发语言·c++·信号处理
_深海凉_10 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展