Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created September 17, 2018 10:54
Show Gist options
  • Save woodRock/b458355670c69854cbff3c1b02257eeb to your computer and use it in GitHub Desktop.
Save woodRock/b458355670c69854cbff3c1b02257eeb to your computer and use it in GitHub Desktop.
Given the root to a binary search tree, find the second largest node in the tree.
#!/usr/bin/env ruby
class Node
attr_accessor :val, :left, :right
def initialize(val, left=nil, right=nil)
@val = val
@left = left
@right = right
end
end
def largest(node)
while node
return node.val if not node.right
node = node.right
end
end
def second(node)
invalid = node.nil? or (node.left.nil? && node.right.nil?)
puts "Tree must have at least 2 nodes" if invalid
while !node.nil?
return largest(node.left) if node.left and not node.right
return node.val if node.right and not node.right.left and not node.right.right
node = node.right
end
end
tree = Node.new('A', Node.new('B'), Node.new('C', left=Node.new('D',Node.new('E'))))
puts second(tree)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment