Different idea to all top solutions in Java.


  • 0
    W

    public class Solution {

    public int countUnivalSubtrees(TreeNode root) {
        return Math.abs(helper(root));
    }
    
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        // When the current subtree is not uni-value, the return value should be negative.
        int res = -(Math.abs(left) + Math.abs(right));
        // Three cases when the current subtree is uni-value.
        if (left > 0 && right > 0 && root.val == root.left.val && root.val == root.right.val) {
            res = 1 + left + right;
        } else if (left > 0 && right == 0 && root.val == root.left.val) {
            res = 1 + left + right;
        } else if (left == 0 && right > 0 && root.val == root.right.val) {
            res = 1 + left + right;
        }
        return res;
    }
    

    }


Log in to reply
 

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