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

二、题解

/**
 * 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;
    }
};

相关推荐

  1. LeetCode965. Univalued Binary Tree

    2023-12-06 23:50:04       52 阅读
  2. LeetCode968. Binary Tree Cameras

    2023-12-06 23:50:04       47 阅读
  3. leetcode905-Sort Array By Parity

    2023-12-06 23:50:04       26 阅读
  4. LeetCode 968.监控二叉树 (hard)

    2023-12-06 23:50:04       48 阅读
  5. LeetCode:967连续查相同的数字(DFS)

    2023-12-06 23:50:04       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-06 23:50:04       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-06 23:50:04       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-06 23:50:04       82 阅读
  4. Python语言-面向对象

    2023-12-06 23:50:04       91 阅读

热门阅读

  1. Android 11.0 所有音量默认为最大音量值

    2023-12-06 23:50:04       52 阅读
  2. 第4章 互联网

    2023-12-06 23:50:04       36 阅读
  3. html页面多个视频标签时设定只能播放一个视频

    2023-12-06 23:50:04       65 阅读
  4. MVCC-

    2023-12-06 23:50:04       50 阅读
  5. 03.PostgreSQL常用索引与优化

    2023-12-06 23:50:04       44 阅读