Skip to content

Commit 44a26b0

Browse files
committed
Add #depth method
1 parent fb9f68f commit 44a26b0

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

lib/tree.rb

+9
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,15 @@ def height(value, node = find(value))
111111
[left_height, right_height].max + 1
112112
end
113113

114+
def depth(value, current_node = @root, result = 0)
115+
return nil if find(value).nil?
116+
return result if value == current_node.data
117+
118+
return depth(value, current_node.left, result + 1) if value < current_node.data
119+
120+
depth(value, current_node.right, result + 1) if value > current_node.data
121+
end
122+
114123
def balanced?
115124
simulated_rebalance = rebalance(change_root: false)
116125
return true if simulated_rebalance == @root

main.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@
2626
puts '--- #postorder ---'
2727
p tree.postorder # returns all nodes in postorder
2828
puts '--- #height ---'
29-
p tree.height(5) # returns 3, the amount of nodes away it is from the lowest leaf
29+
p tree.height(5) # returns 3, the amount of nodes it is from the lowest leaf ("height")
3030
puts '--- #depth ---'
31-
31+
p tree.depth(7) # returns 3, the amount of nodes it is from the root node ("depth")
3232
puts '--- #balanced? ---'
3333
p tree.balanced? # returns true
3434
puts '--- #rebalance ---'

0 commit comments

Comments
 (0)