-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTree.lua
74 lines (61 loc) · 1.26 KB
/
BinarySearchTree.lua
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
local Node = require(script.Node);
Tree = {};
Tree.__index = Tree;
function Tree.new() return setmetatable({ root = nil }, Tree) end
function Tree:insert(element)
local node = Node.new(element);
if (self.root == nil) then
self.root = node;
else
insertNode(self.root, node)
end
end
function insertNode(node, newNode)
if newNode.data < node.data then
node.left = newNode;
if node.left == nil then
node.left = newNode;
else
insertNode(node.left, newNode);
end
else
if node.right == nil then
node.right = newNode;
else
insertNode(node.right, newNode);
end
end
end
function Tree:remove(element)
self.root = removeNode(self.root, element)
end
function removeNode(node, element)
if node == nil then
return nil;
elseif element < node.data then
node.left = removeNode(node.left, element);
return node;
elseif element > node.data then
node.right = removeNode(node.right, element);
return node;
else
if node.left == nil and node.right == nil then
node = nil;
return node;
end
if node.left == nil then
node = node.right;
return node;
elseif node.right == nil then
node = node.left;
return node;
end
end
end
function Tree:isEmpty()
if self.root then
return false;
end
return true;
end
return Tree;