leetcode 501 Find Mode in Binary Search Tree

    xiaoxiao2021-03-26  25

    大致思路:遍历一个二叉树,找出出现次数最多的数字(mode),不过这样的话貌似没有利用到BST这一条件……

    AC代码(Ruby):

    def count_modes(root, modes_hash) unless root.nil? if modes_hash[root.val].nil? modes_hash[root.val] = 1 else modes_hash[root.val] += 1 end count_modes(root.left, modes_hash) count_modes(root.right, modes_hash) end end def find_mode(root) modes_hash = Hash.new count_modes(root, modes_hash) max_count = modes_hash.values.max modes_hash.select{|k, v| v == max_count}.keys end
    转载请注明原文地址: https://ju.6miu.com/read-662735.html

    最新回复(0)