Skip to content

Instantly share code, notes, and snippets.

@kirel
Last active August 29, 2015 13:57
Show Gist options
  • Save kirel/9529322 to your computer and use it in GitHub Desktop.
Save kirel/9529322 to your computer and use it in GitHub Desktop.
def tree_depth tree
# use recursion
# have a look at Array#max
# Hash#empty? might help, too
# your implementation here
end
if __FILE__ == $0
require 'rspec/autorun'
describe 'binary tree depth' do
let(:tree) { {lft:{lft:{lft:{},rgt:{}}},rgt:{lft:{},rgt:{rgt:{}}}} }
let(:ltree) { {lft:{lft:{lft:{}}}} }
let(:rtree) { {rgt:{rgt:{rgt:{}}}} }
it { tree_depth(tree).should == 4 }
it { tree_depth(ltree).should == 4 }
it { tree_depth(rtree).should == 4 }
end
end
Here...
|
|
v
def tree_depth tree
return 0 if tree.nil?
return 1 if tree.empty?
1 + [tree_depth(tree[:lft]), tree_depth(tree[:rgt])].max
end
if __FILE__ == $0
require 'rspec/autorun'
describe 'binary tree depth' do
let(:tree) { {lft:{lft:{lft:{},rgt:{}}},rgt:{lft:{},rgt:{rgt:{}}}} }
let(:ltree) { {lft:{lft:{lft:{}}}} }
let(:rtree) { {rgt:{rgt:{rgt:{}}}} }
it { tree_depth(tree).should == 4 }
it { tree_depth(ltree).should == 4 }
it { tree_depth(rtree).should == 4 }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment