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;
    }
};
相关推荐
菜择贰6 小时前
B树的性质和查找、插入、删除操作
数据结构·b树
LDR0066 小时前
接口焦虑终结者:LDR6020 芯片如何重新定义 Type-C 拓展坞与多设备互联时代
数据结构·经验分享·智能音箱
房开民7 小时前
可变参数模板
java·开发语言·算法
t***5447 小时前
如何在现代C++中更有效地应用这些模式
java·开发语言·c++
_深海凉_7 小时前
LeetCode热题100-最小栈
java·数据结构·leetcode
不知名的忻7 小时前
Morris遍历(力扣第99题)
java·算法·leetcode·morris遍历
状元岐8 小时前
C#反射从入门到精通
java·javascript·算法
itman3018 小时前
C语言、C++与C#深度研究:从底层到现代开发演进全解析
c语言·c++·c·内存管理·编译模型
_深海凉_8 小时前
LeetCode热题100-除了自身以外数组的乘积
数据结构·算法·leetcode
Kk.08029 小时前
项目《基于Linux下的mybash命令解释器》(一)
前端·javascript·算法