-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathDelete-Node-in-a-BST.rb
49 lines (46 loc) · 1.13 KB
/
Delete-Node-in-a-BST.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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