My accepted JAVA solution


  • 0
    J
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        int number = 0;
        public int countUnivalSubtrees(TreeNode root){
            number = 0;
            helper(root);
            return number;
        }
        private boolean helper(TreeNode root){
            if(root ==null) return true;
            if(root.left==null&&root.right==null){
                number++;
                return true;
            }
            boolean left = helper(root.left);
            boolean right = helper(root.right);
            if(!left||!right)return false;
            if(root.left!=null&&root.val != root.left.val) return false;
            if(root.right!=null&&root.val != root.right.val) return false;
            number++;
            return true;
        }
    }
    

Log in to reply
 

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