Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
48 lines (37 loc) · 1013 Bytes

250.md

File metadata and controls

48 lines (37 loc) · 1013 Bytes

250. Count Univalue Subtrees

Description

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example: Given binary tree,

              5
             / \
            1   5
           / \   \
          5   5   5

return 4.

Code

class Solution {
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null){
            return 0;
        }else{
            int leftAndRight = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
            return isUnival(root) ? leftAndRight + 1 : leftAndRight;
        }
    }
    
    boolean isUnival(TreeNode root){
        if(root == null){
            return true;
        }else if(root.left != null && root.val != root.left.val || root.right != null && root.val != root.right.val){
            return false;
        }
        else{
            return isUnival(root.left) && isUnival(root.right);
        }
    }   
}