-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTImplementation.cpp
127 lines (98 loc) · 2.46 KB
/
BSTImplementation.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<bits./stdc++.h>
using namespace std;
class Node{
public:
int val;
Node*left,*right;
Node(int data){
val = data;
left = NULL;
right = NULL;
}
};
Node*insert(Node*root,int val){
if(!root){
Node*temp = new Node(val);
return temp;
}
if(val<root->val)
root->left = insert(root->left,val);
else
root->right = insert(root->right,val);
return root;
}
void InOrder(Node*root){
if(!root) return;
InOrder(root->left);
cout<<root->val<<" ";
InOrder(root->right);
}
bool Search(Node*root,int target){
if(!root) return 0;
if(root->val == target) return 1;
if(target < root->val)
return Search(root->left,target);
else
return Search(root->right,target);
}
int main() {
int arr[8] = {1,2,4,5,6,7,8,9};
Node*root = NULL;
for(int i=0;i<8;i++)
root = insert(root,arr[i]);
InOrder(root);
cout<<endl;
cout<< Search(root,3);
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
// cout.tie(NULL);
class Solution {
public:
vector<Node*>ans;
Node*TreeBuild(int start, int end){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// if(!temp){
// Node*newroot = new Node();
// return newroot;
// }
if(start > end) return NULL;
int mid = (start + end)/2;
Node*temp = ans[mid];
temp ->left = TreeBuild(start,mid-1);
temp -> right = TreeBuild(mid+1,end);
return temp;
}
// vector<int>ans;
void Inorder(Node*root){
if(!root) return;
Inorder(root->left);
ans.push_back(root);
Inorder(root->right);
}
Node* balanceBST(Node* root) {
// vector<int>ans;
if(!root) return NULL;
Inorder(root);
int len = ans.size();
root = TreeBuild(0,len-1);
return root;
// for(int i=0;i<ans.size();i++){
// return TreeBuild(root->left,ans[i]);
// return TreeBuild(root->right,ans[i]);
// }
}
};