# Write better code: Day 7 - Binary Search Tree Arjun Rajkumar Updated on ・1 min read

This post originally appeared on Arjun Rajkumar's blog. Arjun is a web developer based in Bangalore, India.

--

### Day 7: Question 1

Write a method to check that a binary tree is a valid binary search tree.

A binary search tree is a binary tree in which, for each node, the node's value is greater than all values in the left subtree, and the node's value is less than all values in the right subtree.

-

This problem is from InterviewCake.

### Discussion Input: binary tree
Output - Boolean - check if it is a binary search tree ..

Logic:

• Do a depth first search for the tree
• If the child node is on the left, its value has to be lesser than all parents.
• If the child node is on the right, its value has to be greater than all parents.
• So as you go down each node, store the lowest_value and the highest_value.
• Then check if the current is less than the lowest_number (for left side) - and do accordingly for right side.
• Return false if condition not met.
def binary_search_tree(one_tree)

nodes = []
nodes.push([one_tree, -Float::INFINITY, Float::INFINITY])

while nodes.any?
node, lowest_number, highest_number = nodes.pop

return false if ((node.current_value <= lowest_number) || (node.current_value >= highest_number))

nodes.push([node.left, lowest_number, node.current_value]) if node.left
nodes.push([node.left, node.current_value, highest_number]) if node.right
end
true
end


This is in O[n] time.  