AC clean Java solution


  • 7
    public class Solution {
        int count;
        
        public int countUnivalSubtrees(TreeNode root) {
            count = 0;
            helper(root);
            return count;
        }
        
        boolean helper(TreeNode root) {
            if (root == null) return true;
                
            boolean left = helper(root.left);
            boolean right = helper(root.right);
            
            if (left && right && 
               (root.left == null || root.val == root.left.val) && 
               (root.right == null || root.val == root.right.val)) {
                count++;
                return true;
            }
            
            return false;
        }
    }

  • 0

    public class Solution {

    int count=0;
    
    public int countUnivalSubtrees(TreeNode root) {
        
        helper(root);
        return count;
        
    }
    
    public boolean helper(TreeNode root){
        if(root==null) return true;
        
        // from bottom up and only need tranverse once 
        boolean left = helper(root.left);// whether left subtree is univalue
        boolean right = helper(root.right);// whether right subtree is univale
        
        if(left && right){// if both true, check its value with the root
            if(root.left!=null && root.val!= root.left.val)// need to check whether root.left is null since null tree is also univalue
               return false;
               
            if(root.right!=null && root.val !=root.right.val)// need to check whether root.right is null since null tree is also univalue
                return false;
                
            count++;
            
            return true;
        }
        return false;
    }
    

    }


  • 0
    C

    The if (left && right && ()...) check statement is nice!


Log in to reply
 

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