Leetcod刷题(18)——965. 单值二叉树

如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。

只有给定的树是单值二叉树时,才返回 true;否则返回 false。

思路很简单,进行递归遍历即可

class Solution {
    int rootValue = 0;
    public boolean isUnivalTree(TreeNode root) {        
        if(root==null){
            return true;
        }
        rootValue = root.val;
        boolean result = check(root);
        return result;
    }
    public boolean check(TreeNode root){
        if(root==null){
            return true;
        }
        if(root.val!=rootValue){
            return false;
        }
        return check(root.left)&&check(root.right);
    }
}
发布了204 篇原创文章 · 获赞 684 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/u012124438/article/details/102628910