Java solution with DFS


  • 3
    L
    public int countUnivalSubtrees(TreeNode root) {
        // DFS
        int[] ret = new int[1];
        ret[0] = 0;
        IsUnivalue(root, ret);
        return ret[0];
    }
    
    // Return if this tree is Univalue
    private boolean IsUnivalue(TreeNode root, int[] ret)
    {
        if(root == null)
            return true;
        
        boolean isLeft = IsUnivalue(root.left, ret);
        boolean isRight = IsUnivalue(root.right, ret);
        if(!isLeft || !isRight)
            return false;
            
        if(root.left != null && root.val != root.left.val)
            return false;
    
        if(root.right != null && root.val != root.right.val)
            return false;
        
        ret[0] += 1;
        return true;
    }

Log in to reply
 

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