Java solution, short but somewhat ugly


  • 0
    A
    public int countUnivalSubtrees(TreeNode root) {
        int[] res = new int[1];
        getSubtree(root, res);
        return res[0];
    }
    
    private int getSubtree(TreeNode root, int[] res) {
        if (root == null) return Integer.MIN_VALUE;
        int l = getSubtree(root.left, res);
        int r = getSubtree(root.right, res);
        if ((l == Integer.MIN_VALUE && r == Integer.MIN_VALUE)
            || (r == Integer.MIN_VALUE && l == root.val) 
            || (l == Integer.MIN_VALUE && r == root.val)
            || (r == l && r == root.val)){
            res[0]++;
            return root.val;
        }
        return Integer.MAX_VALUE;
    }

  • 0

    Your title is buggy :-P

    And you can do:

        if ((l == Integer.MIN_VALUE || l == root.val) &&
            (r == Integer.MIN_VALUE || r == root.val)){
    

    Though it remains broken, as you fail for example the input [0,-2147483648]. Hmm... I'm beginning to think that the title isn't an unintentional typo after all...


  • 0
    A

    Indeed I can :) Also, fixed the bug :)


Log in to reply
 

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