-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array to BST.cpp
124 lines (98 loc) · 2.32 KB
/
Array to BST.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val)
: data(val)
, left(nullptr)
, right(nullptr) {}
};
bool help(Node* root, long long int up, long long int l) {
if (root->data >= up || root->data <= l)
return false;
bool ans = true;
if (root->left)
ans = help(root->left, root->data, l);
if (ans && root->right)
ans = help(root->right, up, root->data);
return ans;
}
bool isValidBST(Node* root) {
return help(root, 3147483648, -3147483649);
}
int Height(Node* root) {
if (root == NULL)
return 0;
int leftHeight = Height(root->left);
int rightHight = Height(root->right);
if (leftHeight == -1 || rightHight == -1 || abs(leftHeight - rightHight) > 1)
return -1;
return max(leftHeight, rightHight) + 1;
}
bool isBalanced(Node* root) {
if (root == NULL)
return true;
if (Height(root) == -1)
return false;
return true;
}
// } Driver Code Ends
/*
struct Node {
int data;
Node* left;
Node* right;
Node(int val)
: data(val)
, left(nullptr)
, right(nullptr) {}
};
*/
class Solution {
public:
Node* solve(vector<int>&nums,int start, int end ){
if(start>end) return NULL;
int mid = start+(end-start)/2;
Node* root = new Node(nums[mid]);
root->left = solve(nums,start,mid-1);
root->right = solve(nums,mid+1,end);
return root;
}
Node* sortedArrayToBST(vector<int>& nums) {
// Code here
return solve(nums,0,nums.size()-1);
}
};
//{ Driver Code Starts.
int main() {
int t;
cin >> t;
cin.ignore();
while (t--) {
vector<int> arr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
Solution ob;
Node* a = ob.sortedArrayToBST(arr);
if (!isValidBST(a)) {
cout << "false" << endl;
return 0;
}
bool f = isBalanced(a);
if (f)
cout << "true";
else
cout << "false";
cout << "\n";
}
return 0;
}
// } Driver Code Ends