ruby simple solution


  • 0
    C

    The hard part is having to store a counter just like Python. Since there is no way to access a variable that is outside the dfs function, so we can have a workaround by creating a Count class to store the max.
    class Count
    attr_accessor :count
    def initialize(count=0)
    @count = count
    end

    end
    def diameter_of_binary_tree(root)
    count = Count.new()
    def dfs(root,count)
    return 0 if root.nil?
    left, right = dfs(root.left,count), dfs(root.right,count)
    count.count = [count.count,left + right].max
    1 + [left,right].max
    end
    dfs(root,count)
    count.count
    end


Log in to reply
 

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