-
Notifications
You must be signed in to change notification settings - Fork 46
/
BasicBST.cpp
96 lines (77 loc) · 2.13 KB
/
BasicBST.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
*
*DELETING A NODE
*
*/
Node *deleteNode(Node *root, int x)
{
// root can be null
if (!root) return NULL;
// search for the value
if ( root ->data < x )
root -> right = deleteNode( root-> right , x);
else if ( root->data > x)
root -> left = deleteNode( root->left , x);
//equal
else{
// only one child or no child
if ( !root->left){
Node* temp = root -> right;
free(root);
return temp;
}
else if ( !root->right){
Node* temp = root -> left;
free(root);
return temp;
}
// both children present
else{
// find inorder successor
Node *successor = root-> right;
while( successor && successor-> left)
successor = successor-> left;
//replace the root data
root->data = successor-> data;
//delete the successor
root->right = deleteNode(root-> right , successor->data);
}
}
return root;
}
/**
*
*Predecessor and Successor of a node
*
*/
void findPreSuc(Node* root, Node*& pre, Node*& succ, int key)
{
// preorder traversal
if (!root) return ;
findPreSuc( root->left , pre , succ , key);
// take the last node in the traversal
if ( root->data < key) pre = root;
// take the first node more than key
if ( root->data > key && !succ) succ = root;
findPreSuc( root->right , pre, succ , key);
}
/**
*
* Constructing BST from preorder traversal array
*/
TreeNode* util( vector<int> pre, int &index , int mx ,int mn){
if ( index == pre.size() )return nullptr;
int val = pre[index];
if ( val > mx || val < mn) return nullptr;
TreeNode * root = new TreeNode( val);
index++;
root-> left = util( pre, index , val-1, mn);
root -> right = util (pre, index, mx, val+1);
return root;
}
TreeNode* bstFromPreorder(vector<int>& preorder) {
if ( preorder.empty()) return NULL;
int p =0;
TreeNode* root = util( preorder , p , INT_MAX ,INT_MIN);
return root;
}