Java concise 8-liner 1ms solution


  • 0
    public class Solution {
        public int countUnivalSubtrees(TreeNode root)  return Math.abs(helper(root)); 
        private int helper(TreeNode root){
            if(null==root) return 0; 
            int l = helper(root.left), r = helper(root.right);
            if(l<0 || r<0 || (null!=root.left && root.val!=root.left.val) || (null!=root.right && root.val!=root.right.val)){
                return -Math.abs(l)-Math.abs(r);
            }
            return l+r+1;
        }
    }
    

    Helper function returns number of univalue subtrees. Here I used negative numbers to indicate current tree is not a univalue tree. I guess there may be overflow issues, although OJ did not test it.


Log in to reply
 

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