Skip to content

Commit 3507dd6

Browse files
committed
add: cpp: 7-98
1 parent 7caca40 commit 3507dd6

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// 98: Validate Binary Search Tree
2+
// https://leetcode.com/problems/validate-binary-search-tree/
3+
4+
5+
6+
#include <iostream>
7+
#include <queue>
8+
#include <vector>
9+
#include <stack>
10+
11+
using namespace std;
12+
13+
struct TreeNode {
14+
int val;
15+
TreeNode *left;
16+
TreeNode *right;
17+
TreeNode() : val(0), left(nullptr), right(nullptr) {}
18+
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
19+
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
20+
};
21+
22+
TreeNode* creator(vector<int> values, TreeNode** root, int i, int n) {
23+
if (n==0) return NULL;
24+
if (i<n) {
25+
TreeNode *temp = new TreeNode(values[i]);
26+
*root = temp;
27+
(*root)->left = creator(values, &((*root)->left), 2*i+1, n);
28+
(*root)->right = creator(values, &((*root)->right), 2*i+2, n);
29+
}
30+
return *root;
31+
};
32+
33+
void createTree(TreeNode** root, vector<int> inputs) {
34+
creator(inputs, root, 0, inputs.size());
35+
}
36+
37+
void showTree(TreeNode* root) {
38+
queue<TreeNode*> q;
39+
vector<vector<int>> result = {};
40+
vector<int> c;
41+
if (root==NULL) { cout << "Empty !" << endl; return; }
42+
q.push(root);
43+
q.push(NULL);
44+
while (!q.empty()) {
45+
TreeNode *t = q.front();
46+
q.pop();
47+
if (t==NULL) {
48+
result.push_back(c);
49+
c.resize(0);
50+
if (q.size() > 0) q.push(NULL);
51+
} else {
52+
c.push_back(t->val);
53+
if (t->left) q.push(t->left);
54+
if (t->right) q.push(t->right);
55+
}
56+
}
57+
58+
cout<<"["; for (auto x : result) {
59+
cout<<"["; for (auto y : x) {
60+
if (!y) { cout << "NULL,"; continue; }
61+
cout<<y<<",";
62+
} cout<<"\b],";
63+
} cout<<"\b]"<<endl;
64+
}
65+
66+
67+
68+
class Solution {
69+
private:
70+
bool traverse(TreeNode *root, TreeNode* min, TreeNode* max) {
71+
if (root==NULL) return true;
72+
if (min && root->val<=min->val) return false;
73+
if (max && root->val>=max->val) return false;
74+
75+
bool l = traverse(root->left, min, root);
76+
bool r = traverse(root->right, root, max);
77+
78+
return l && r;
79+
}
80+
81+
public:
82+
// SOLUTION
83+
bool isValidBST(TreeNode* root) {
84+
return traverse(root, NULL, NULL);
85+
}
86+
};
87+
88+
89+
90+
int main() {
91+
Solution o;
92+
TreeNode* root = NULL;
93+
94+
// INPUT
95+
vector<int> tn = {2,1,3};
96+
createTree(&root, tn);
97+
98+
// OUTPUT
99+
auto result = o.isValidBST(root);
100+
cout << (result ? "true" : "false") << endl;
101+
102+
return 0;
103+
}

0 commit comments

Comments
 (0)