-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInsertNodeInBST.h
More file actions
61 lines (51 loc) · 1.25 KB
/
InsertNodeInBST.h
File metadata and controls
61 lines (51 loc) · 1.25 KB
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
/*
bluepp
2014-12-22
May the force be with me!
Insert a node to a BST tree
Binary search tree. Adding a value
*/
/*http://www.algolist.net/Data_structures/Binary_search_tree/Insertion */
bool BinarySearchTree::add(int value) {
if (root == NULL) {
root = new BSTNode(value);
return true;
} else
return root->add(value);
}
bool BSTNode::add(int value) {
if (value == this->value)
return false;
else if (value < this->value) {
if (left == NULL) {
left = new BSTNode(value);
return true;
} else
return left->add(value);
} else if (value > this->value) {
if (right == NULL) {
right = new BSTNode(value);
return true;
} else
return right->add(value);
}
return false;
}
TreeNode * add(TreeNode *root, int val)
{
if (!root)
{
TreeNode *root = new TreeNode (val);
return root;
}
if (val == root->val) return ?
if (val < root->val)
{
root->left = add(root->left, val);
}
else
{
root->right = add(root->right, val);
}
return root;
}