Very Simple Java Recursive Solution, just 5 line!!!


  • 0
    H
    public int countUnivalSubtrees(TreeNode root) {
            if(root == null) return 0;
            
            return isUnitree(root, root.val) + countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
        }
        
        private int isUnitree(TreeNode root, int value){
            if(root == null) return 1;
            
            if(root.val == value && isUnitree(root.left, value) == 1 && isUnitree(root.right, value) == 1) return 1;
            return 0;
        }

  • 0

    what's time and space of this solution? both are O(n) ?


  • 0
    Y
    This post is deleted!

Log in to reply
 

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