7-line accepted code in Java


  • 5
    C
    public class Solution {
        int count = 0;
        public int countUnivalSubtrees(TreeNode root) {
            return (root==null || isUni(root)) ? count : count;
        }
        public boolean isUni(TreeNode root){
            boolean left = root.left == null || isUni(root.left) && root.val == root.left.val;
            boolean right = root.right == null || isUni(root.right) && root.val == root.right.val;
            return left && right && ++count==count;
        }
    }

  • 0
    R

    Really curious about ++count==count in the last line, can you explain that?


  • 0
    C

    ++count==count is always true. In this way we could save another sentence to write count++. In C, we can write "++count, left && right". We cannot use "," in java.


  • 0

    my solution in 9-line but without global variable, the idea is similar

        public int countUnivalSubtrees(TreeNode root) {
            if (root == null) {return 0;}
            int sub = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
            return isU(root, root.val) ? sub + 1 : sub;
        }
        
        public boolean isU(TreeNode root, int val) {
            if (root == null) {return true;}
            if (root.val != val) {return false;}
            return isU(root.left, val) && isU(root.right, val);
        }
    

Log in to reply
 

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