Java Solution using recursion


  • 0
    C
        public int countUnivalSubtrees(TreeNode root) {
            countSubTree(root);
            return count;
        }
        
        private int count = 0;
        
        private boolean countSubTree(TreeNode node){
            if(node == null){
                return true;
            }
            
            boolean leftSubTree = countSubTree(node.left);
            boolean rightSubTree = countSubTree(node.right);
            
            boolean unival = true;
            
            if(node.left != null){
                unival = node.left.val == node.val;
            }
            
            if(node.right != null){
                unival = node.right.val == node.val && unival;
            }
            
            if(unival && leftSubTree && rightSubTree){
                count++;
            }
            
            return unival && leftSubTree && rightSubTree;
        }
    

Log in to reply
 

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