Created
September 17, 2018 10:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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