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人山人海22 分钟前
现代c++4.1
java·开发语言·c++
Pniubi1 小时前
贪心算法入门
算法·贪心算法
MobotStone1 小时前
AI 能不能越用越会用?从“改答案”到“改进自己”,读懂 RSI
人工智能·算法
复杂网络与机器学习2 小时前
Meta 重写 K-Means:25 轮压成 2 轮,GPU 快 45 倍
人工智能·算法·数据挖掘
lunar_coder2 小时前
【算法】前缀和:把 O(n) 的重复劳动变成 O(1) 的一次查询
c++·算法
Pniubi2 小时前
力扣19 . 删除表的倒数第N个节点(栈)
算法·leetcode·职场和发展
青少儿编程课堂3 小时前
第十八届蓝桥杯青少组图形化 + 全国青少年信息素养大赛 + 电子学会图形化考级:校园三消乐大挑战解析
c++·python·算法·bfs·信息学竞赛
青少儿编程课堂3 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:网格连通块与岛屿数量(DFS+BFS双解)
c++·python·算法·bfs·信息学竞赛
码客-ygluu11 小时前
X3 LUA 异步分布式微服务集群框架
c++·架构·lua
forest_0914 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi