Skip to content

Commit 01fdb77

Browse files
committed
fix insert!, and write delete!
1 parent aa695b3 commit 01fdb77

File tree

1 file changed

+87
-3
lines changed

1 file changed

+87
-3
lines changed

src/avl_tree.jl

Lines changed: 87 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,10 @@ function Base.insert!(tree::AVLTree{K}, d::K) where K
7575
else
7676
node.rightChild = insert_node(node.rightChild, key)
7777
end
78-
78+
79+
node.height = fix_height(node)
7980
balance = get_balance(node)
81+
8082
if balance > 1
8183
if key < node.leftChild.data
8284
return right_rotate(node)
@@ -97,8 +99,90 @@ function Base.insert!(tree::AVLTree{K}, d::K) where K
9799

98100
return node
99101
end
100-
101102
tree.root = insert_node(tree.root, d)
102103
return tree
104+
end
105+
106+
function Base.delete!(tree::AVLTree{K}, d::K) where K
107+
108+
function delete_node(node::Union{AVLTreeNode, Nothing}, key)
109+
if node == nothing || node.data == nothing
110+
return nothing
111+
elseif key < node.data
112+
node.leftChild = delete_node(node.leftChild, key)
113+
elseif key > node.data
114+
node.rightChild = delete_node(node.rightChild, key)
115+
else
116+
if node.leftChild == nothing
117+
temp = node.rightChild
118+
node = nothing
119+
return temp
120+
elseif node.rightChild == nothing
121+
temp = node.leftChild
122+
node = nothing
123+
return temp
124+
else
125+
temp = get_minimum_node(node.rightChild)
126+
node.data = temp.data
127+
node.rightChild = delete_node(node.rightChild, temp.data)
128+
end
129+
end
130+
131+
if node == nothing
132+
return node
133+
end
134+
135+
node.height = fix_height(node)
136+
balance = get_balance(node)
137+
138+
if balance > 1
139+
if get_balance(node.leftChild) >= 0
140+
return right_rotate(node)
141+
else
142+
node.leftChild = left_rotate(node.leftChild)
143+
return right_rotate(node)
144+
end
145+
end
146+
147+
if balance < -1
148+
if get_balance(node.rightChild) <= 0
149+
return left_rotate(node)
150+
else
151+
node.rightChild = right_rotate(node.rightChild)
152+
return left_rotate(node)
153+
end
154+
end
155+
156+
return node
157+
end
158+
159+
tree.root = delete_node(tree.root, d)
160+
return tree
161+
end
162+
163+
function print_tree(tree::AVLTree)
164+
function print_tree_helper(node::AVLTreeNode_or_null, indent, isright)
165+
if node != nothing && node.data != nothing
166+
print(indent)
167+
if isright
168+
print("R--")
169+
indent *= " "
170+
else
171+
if (node == tree.root)
172+
print("-->")
173+
indent *= " "
174+
else
175+
print("L--")
176+
indent *= "| "
177+
end
178+
179+
end
180+
println(node.data, " (", get_balance(node), ")" , "H[", get_height(node), "]")
181+
print_tree_helper(node.leftChild, indent, false)
182+
print_tree_helper(node.rightChild, indent, true)
183+
end
184+
end
185+
print_tree_helper(tree.root, "", false)
186+
end
103187

104-
end
188+
Base.show(io::IO, t::AVLTree) = print_tree(t)

0 commit comments

Comments
 (0)