Clear Ruby Solution with Hashmap


  • 0
    R
    def find_frequent_tree_sum(root)
        sum_freqs = Hash.new(0)
        populate_sums(root, sum_freqs)
        max_freq = sum_freqs.values.max
        sum_freqs.map{ |key, value| value == max_freq ? key : nil }.compact
    end
    
    def populate_sums(root, sum_freqs)
       return 0 if root.nil?
       
       left_sum = populate_sums(root.left, sum_freqs)
       right_sum = populate_sums(root.right, sum_freqs)
       
       sum = left_sum + right_sum + root.val
       sum_freqs[sum] += 1
       sum
    end
    

    Would love suggestions on improving this :)


Log in to reply
 

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