problems: add insert-into-a-bst
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
2ba0b3930a
commit
16763cdd2f
1 changed files with 36 additions and 0 deletions
36
problems/insert-into-a-binary-search-tree.rb
Normal file
36
problems/insert-into-a-binary-search-tree.rb
Normal file
|
@ -0,0 +1,36 @@
|
||||||
|
# Definition for a binary tree node.
|
||||||
|
# class TreeNode
|
||||||
|
# attr_accessor :val, :left, :right
|
||||||
|
# def initialize(val = 0, left = nil, right = nil)
|
||||||
|
# @val = val
|
||||||
|
# @left = left
|
||||||
|
# @right = right
|
||||||
|
# end
|
||||||
|
# end
|
||||||
|
# @param {TreeNode} root
|
||||||
|
# @param {Integer} val
|
||||||
|
# @return {TreeNode}
|
||||||
|
def insert_into_bst(root, val)
|
||||||
|
new_node = TreeNode.new(val)
|
||||||
|
if root == nil then
|
||||||
|
return new_node
|
||||||
|
end
|
||||||
|
|
||||||
|
node = root
|
||||||
|
while (val < node.val && node.left != nil) || (val >= node.val && node.right != nil) do
|
||||||
|
if val < node.val then
|
||||||
|
node = node.left
|
||||||
|
else
|
||||||
|
node = node.right
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# insert the node
|
||||||
|
if val < node.val then
|
||||||
|
node.left = new_node
|
||||||
|
else
|
||||||
|
node.right = new_node
|
||||||
|
end
|
||||||
|
|
||||||
|
return root
|
||||||
|
end
|
Loading…
Reference in a new issue