[LeetCode] 965. Univalued Binary Tree 单值二叉树


A binary tree is univalued if every node in the tree has the same value.

Return true if and only if the given tree is univalued.

Example 1:

Input: [1,1,1,1,1,null,1]
Output: true

Example 2:

Input: [2,2,2,5,2]
Output: false

Note:

  1. The number of nodes in the given tree will be in the range [1, 100].
  2. Each node's value will be an integer in the range [0, 99].

这道题定义了一种单值二叉树,需要二叉树中所有的结点值相同。先给了一棵二叉树,问是不是单值二叉树。其实就是考察遍历二叉树,当然递归的方法在写法上最简单了。这里可以将每个结点值都跟根结点值进行比较,只要任意一个不相同,则表示不是单值二叉树。所以需要将根结点值当个参数代入递归函数,所以写一个 helper 函数,进行先序遍历的递归写法即可,参见代码如下:


解法一:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        return helper(root, root->val);
    }
    bool helper(TreeNode* node, int val) {
        if (!node) return true;
        if (node->val != val) return false;
        return helper(node->left, val) && helper(node->right, val);
    }
};

当然我们也可以不写额外的子函数,在一个函数比较,只要任意一个结点的左右子结点值(存的的话)均和其父结点值相等,则一定是单值二叉树。所以在一个函数中也可以进行比较,参见代码如下:


解法二:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        if (root->left && root->left->val != root->val) return false;
        if (root->right && root->right->val != root->val) return false;
        return isUnivalTree(root->left) && isUnivalTree(root->right);
    }
};

上面的解法都是递归写法,来看迭代写法的层序遍历吧,解题思路并没有什么不同,就只是遍历的方法不同而已,参见代码如下:


解法三:

class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if (!root) return true;
        queue<TreeNode*> q{{root}};
        while (!q.empty()) {
            TreeNode* t = q.front(); q.pop();
            if (t->val != root->val) return false;
            if (t->left) q.push(t->left);
            if (t->right) q.push(t->right);
        }
        return true;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/965


类似题目:

Find All The Lonely Nodes


参考资料:

https://leetcode.com/problems/univalued-binary-tree/

https://leetcode.com/problems/univalued-binary-tree/discuss/211190/JavaC%2B%2BPython-Straight-Forward

https://leetcode.com/problems/univalued-binary-tree/discuss/252904/C%2B%2B-4-Lines-of-Code-Beats-100-Easy-to-Understand

https://leetcode.com/problems/univalued-binary-tree/discuss/211397/JavaPython-3-BFS-and-DFS-clean-codes-w-brief-analysis.


LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2020-12-10 13:51  Grandyang  阅读(549)  评论(0编辑  收藏  举报
Fork me on GitHub