Skip to content

Commit f5888ab

Browse files
committed
Validate BST
1 parent 2efb295 commit f5888ab

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// VALIDATE BINARY SEARCH TREE --->> LEETCODE
2+
3+
4+
5+
// Given the root of a binary tree, determine if it is a valid binary search tree (BST).
6+
7+
// A valid BST is defined as follows:
8+
9+
// The left
10+
// subtree
11+
// of a node contains only nodes with keys less than the node's key.
12+
// The right subtree of a node contains only nodes with keys greater than the node's key.
13+
// Both the left and right subtrees must also be binary search trees.
14+
15+
// ALGORITHM-->
16+
// Follow these steps while the current node is not null:
17+
// Process the current node and go to its right child if it doesn't have a left child.
18+
// Find the inorder predecessor of the current node—that is, the rightmost node in the left subtree—if the present node has a left child, and see if its value is smaller than the value of the current node.
19+
20+
// If the predecessor's right child is null, go to the current node's left child and change the predecessor's right child to point to it.
21+
// In order to restore the binary tree's original structure, reset the predecessor's right child to null, process the current node, and then move to its right child if it is already referring to the current node.
22+
23+
24+
25+
26+
27+
#include <bits/stdc++.h>
28+
using namespace std;
29+
30+
struct Node {
31+
int data;
32+
struct Node *left, *right;
33+
34+
Node(int data)
35+
{
36+
this->data = data;
37+
left = right = NULL;
38+
}
39+
};
40+
41+
42+
bool validate(Node* root,long long int min , long long int max){
43+
if(!root)
44+
return true;
45+
bool ans = false;
46+
if(root->data<max && root->data>min)
47+
ans = true;
48+
else
49+
return ans;
50+
return ans && validate(root->left,min,root->data) &&
51+
validate(root->right,root->data,max);
52+
}
53+
54+
55+
bool isValidBST(Node* root) {
56+
if(!root)
57+
return true;
58+
return validate(root ,-9223372036854775807,9223372036854775807 );
59+
}
60+
61+
int main()
62+
{
63+
struct Node* root = new Node(3);
64+
root->left = new Node(2);
65+
root->right = new Node(5);
66+
root->left->left = new Node(1);
67+
root->left->right = new Node(4);
68+
69+
if (isValidBST(root))
70+
cout << "Is BST";
71+
else
72+
cout << "Not a BST";
73+
74+
return 0;
75+
}
76+
77+
78+
79+
80+
// T.C. O(N)
81+
// S.C. O(N) ---> for Auxillary stack

0 commit comments

Comments
 (0)