Skip to content

Commit aa695b3

Browse files
committed
write code for AVLTree insert!
1 parent 71585bb commit aa695b3

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

src/avl_tree.jl

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
mutable struct AVLTreeNode{K}
2+
height::Int8
3+
data::K
4+
leftChild::Union{AVLTreeNode{K}, Nothing}
5+
rightChild::Union{AVLTreeNode{K}, Nothing}
6+
7+
AVLTreeNode{K}() where K = new{K}(0, nothing, nothing, nothing)
8+
AVLTreeNode{K}(d::K) where K = new{K}(1, d, nothing, nothing)
9+
end
10+
11+
AVLTreeNode(d) = AVLTreeNode{Any}(d)
12+
13+
AVLTreeNode_or_null{T} = Union{AVLTreeNode{T}, Nothing}
14+
15+
mutable struct AVLTree{T}
16+
root::AVLTreeNode_or_null{T}
17+
18+
AVLTree{T}() where T = new{T}(AVLTreeNode{T}())
19+
end
20+
21+
AVLTree() = AVLTree{Any}()
22+
23+
function get_height(node::Union{AVLTreeNode, Nothing})
24+
if node == nothing
25+
return 0
26+
else
27+
return node.height
28+
end
29+
end
30+
31+
function get_balance(node::Union{AVLTreeNode, Nothing})
32+
if node == nothing
33+
return 0
34+
else
35+
return get_height(node.leftChild) - get_height(node.rightChild)
36+
end
37+
end
38+
39+
fix_height(node::Union{AVLTreeNode, Nothing}) = 1 + max(get_height(node.leftChild), get_height(node.rightChild))
40+
41+
function left_rotate(z::AVLTreeNode)
42+
y = z.rightChild
43+
α = y.leftChild
44+
y.leftChild = z
45+
z.rightChild = α
46+
z.height = fix_height(z)
47+
y.height = fix_height(y)
48+
return y
49+
end
50+
51+
function right_rotate(z::AVLTreeNode)
52+
y = z.leftChild
53+
α = y.rightChild
54+
y.rightChild = z
55+
z.leftChild = α
56+
z.height = fix_height(z)
57+
y.height = fix_height(y)
58+
return y
59+
end
60+
61+
function get_minimum_node(node::Union{AVLTreeNode, Nothing})
62+
while node != nothing && node.leftChild != nothing
63+
node = node.leftChild
64+
end
65+
return node
66+
end
67+
68+
function Base.insert!(tree::AVLTree{K}, d::K) where K
69+
70+
function insert_node(node::Union{AVLTreeNode, Nothing}, key)
71+
if node == nothing || node.data == nothing
72+
return AVLTreeNode{K}(key)
73+
elseif key < node.data
74+
node.leftChild = insert_node(node.leftChild, key)
75+
else
76+
node.rightChild = insert_node(node.rightChild, key)
77+
end
78+
79+
balance = get_balance(node)
80+
if balance > 1
81+
if key < node.leftChild.data
82+
return right_rotate(node)
83+
else
84+
node.leftChild = left_rotate(node.leftChild)
85+
return right_rotate(node)
86+
end
87+
end
88+
89+
if balance < -1
90+
if key > node.rightChild.data
91+
return left_rotate(node)
92+
else
93+
node.rightChild = right_rotate(node)
94+
return left_rotate(node)
95+
end
96+
end
97+
98+
return node
99+
end
100+
101+
tree.root = insert_node(tree.root, d)
102+
return tree
103+
104+
end

0 commit comments

Comments
 (0)