My Java solution using a boolean helper function

  • 0
    public int countUnivalSubtrees(TreeNode root) {
        if(root==null) return 0;
        if(root.left==null && root.right==null) return 1;
        int result=countUnivalSubtrees(root.left)+countUnivalSubtrees(root.right);
        if(helper(root)) result++;
        return result;
    public boolean helper(TreeNode root){
        if(root==null) return true;
        if(!helper(root.left) || (root.left!=null && root.left.val!=root.val)) return false;
        if(!helper(root.right) ||(root.right!=null && root.right.val!=root.val)) return false;
        return true;

Log in to reply

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