965.单值二叉树
链接:965.单值二叉树
难度:Easy
标签:树、深度优先搜索、广度优先搜索、二叉树
简介:如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
题解 1 - cpp
- 编辑时间:2022-05-24
- 内存消耗:9.6MB
- 编程语言:cpp
- 解法介绍:dfs。
class Solution {
   public:
    int val = 0;
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        if (val == 0) val = root->val;
        return root->val == val && isUnivalTree(root->left) &&
               isUnivalTree(root->right);
    }
};
题解 2 - cpp
- 编辑时间:2022-05-24
- 内存消耗:9.5MB
- 编程语言:cpp
- 解法介绍:dfs。
class Solution {
   public:
    bool isUnivalTree(TreeNode* root) { return _isUnivalTree(root, root->val); }
    bool _isUnivalTree(TreeNode* node, int val) {
        if (node == nullptr) return true;
        return node->val == val && _isUnivalTree(node->left, val) &&
               _isUnivalTree(node->right, val);
    }
};
题解 3 - cpp
- 编辑时间:2022-03-25
- 执行用时:4ms
- 内存消耗:9.6MB
- 编程语言:cpp
- 解法介绍:dfs。
class Solution {
   public:
    bool isUnivalTree(TreeNode* root) { return dfs(root, root->val); }
    bool dfs(TreeNode* node, int val) {
        if (!node) return true;
        if (node->val != val) return false;
        return dfs(node->left, val) && dfs(node->right, val);
    }
};