-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfind_longest_branch_in_a_tree.rb
More file actions
45 lines (35 loc) · 1.01 KB
/
find_longest_branch_in_a_tree.rb
File metadata and controls
45 lines (35 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
require 'pry'
class Node
attr_accessor :value, :left, :right, :name
def initialize(options={})
@value = options[:value]
@name = options[:name]
end
def children
[@left, @right].compact
end
def children?
@left && @right
end
def no_children?
@left.nil? && @right.nil?
end
end
root = Node.new({:value => 1, :name => 'root'})
child_1 = Node.new({:value => 2, :name => 'child_1'})
child_2 = Node.new({:value => 3, :name => 'child_2'})
grand_child_1 = Node.new({:value => 4, :name => 'grand_child_1'})
grand_grand_child_1 = Node.new({:value => 5, :name => 'grand_grand_child_1'})
grand_child_1.left = grand_grand_child_1
child_1.left = grand_child_1
root.left = child_1
root.right = child_2
def maximum_branch(node)
return [[], 0] if node.nil?
left, length_l = maximum_branch(node.left)
right, length_r = maximum_branch(node.right)
length_l > length_r ? [left<<node, length_l+1] : [right<<node, length_r+1]
end
nodes, length = maximum_branch(root)
puts nodes.map(&:value)
puts length