Skip to content

Instantly share code, notes, and snippets.

@intrip
Created April 11, 2020 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrip/66a67309c699c7d679c27a9aadb2a40c to your computer and use it in GitHub Desktop.
Save intrip/66a67309c699c7d679c27a9aadb2a40c to your computer and use it in GitHub Desktop.
# Definition for a binary tree node.
# class TreeNode
# attr_accessor :val, :left, :right
# def initialize(val)
# @val = val
# @left, @right = nil, nil
# end
# end
# @param {TreeNode} root
# @return {Integer}
def diameter_of_binary_tree(root)
return 0 unless root
graph = [Node.new(root.val)]
build_graph(root, graph[0], graph)
ans = 0
graph.each do |g_node|
visited = Set.new
$max = 0
dfs(g_node, visited)
ans = [ans, $max].max
end
ans
end
def dfs(node, visited, dst = 0)
visited << node
node.adj.each do |neighbour|
next if visited.include?(neighbour)
visited << neighbour
dfs(neighbour, visited, dst + 1)
end
$max = [$max, dst].max
end
def build_graph(tree_node, g_node, graph)
if tree_node.left
left = Node.new(tree_node.left.val)
g_node.adj << left
left.adj << g_node
graph << left
build_graph(tree_node.left, left, graph)
end
if tree_node.right
right = Node.new(tree_node.right.val)
g_node.adj << right
right.adj << g_node
graph << right
build_graph(tree_node.right, right, graph)
end
g_node
end
class Node
attr_reader :val
attr_accessor :adj
def initialize(val)
@val = val
@adj = []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment