Java simple clean recursive solution


  • 0
    J
    public class Solution {
    public int countUnivalSubtrees(TreeNode root) {
    	if (root == null) return 0;
    	int count = 0;
    	if (isUnivalTree(root))
    		count = 1;
    	return countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right) + count;
    }
    
    private boolean isUnivalTree(TreeNode root) {
    	boolean univalLeft = true, univalRight = true;
    	if (root.left != null) {
    		if (root.val != root.left.val)
    			return false;
    		else 
    			univalLeft = isUnivalTree(root.left);
    	}
    	if (root.right != null) {
    		if (root.val != root.right.val) 
    			return false;
    		else
    			univalRight = isUnivalTree(root.right);
    			
    	}
    	return univalLeft && univalRight;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.