-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion_BST.cpp
More file actions
38 lines (34 loc) · 800 Bytes
/
Insertion_BST.cpp
File metadata and controls
38 lines (34 loc) · 800 Bytes
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
#include <bits/stdc++.h>
using namespace std;
struct BstNode
{
int data;
BstNode* left;
BstNode* right;
};
BstNode* GetNewNode(int data) {
BstNode* newNode = new BstNode();
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// ALways return the rootPtr coz we need to store it in root->left/right when doing recursion & also in int main fn
BstNode* InsertNode(BstNode* rootPtr, int data) {
if (rootPtr == NULL) {
rootPtr = GetNewNode(data);
}
else if(data <= rootPtr->data) {
rootPtr->left = InsertNode(rootPtr->left, data);
}
else {
rootPtr->right = InsertNode(rootPtr->right, data);
}
return rootPtr;
}
int main() {
BstNode* rootPtr = NULL;
int data;
cout << "Give node data : " << endl;
cin >> data;
rootPtr = InsertNode(rootPtr, data);
}