Skip to content

add delete_node_in_a_bst onn ruby version #278

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 3, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 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} key
# @return {TreeNode}
def delete_node(root, key)
if root == nil
return root
elsif root.val > key
root.left = delete_node(root.left, key)

elsif root.val < key
root.right = delete_node(root.right, key)

else
if root.left == nil && root.right == nil
root = nil
return nil
elsif root.left == nil
tmp = root.right
root = nil
return tmp
elsif root.right == nil
tmp = root.left
root = nil
return tmp
else
tmp = min_value(root.right)
root.val = tmp.val
root.right = delete_node(root.right, tmp.val)
end
end
return root
end

def min_value(node)
current = node
while current.left != nil
current = current.left
end
current
end