You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 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
+
// C++ program to check if a given tree is BST.
28
+
#include<bits/stdc++.h>
29
+
usingnamespacestd;
30
+
31
+
32
+
33
+
structNode {
34
+
// structure of a node of the tree.
35
+
int data;
36
+
structNode *left, *right;
37
+
38
+
Node(int data)
39
+
{
40
+
this->data = data;
41
+
left = right = NULL;
42
+
}
43
+
};
44
+
45
+
46
+
boolvalidate(Node* root,longlongint min , longlongint max){
47
+
if(!root)
48
+
returntrue; // if the root is null then it is a valid BST. it means that the tree is empty or we had reached the end of tree.
49
+
// initializing the ans variable to false (temporarily).
50
+
bool ans = false;
51
+
52
+
// checking if the root's data is in the range of min and max.
53
+
if(root->data<max && root->data>min)
54
+
ans = true;
55
+
else
56
+
return ans; // if the root's data is not in the range of min and max then it is not a valid BST. hence returning false.
57
+
58
+
// changing min and max for the left and right subtree. and checking for the left and right subtree with respesct to tree root and returning the ans.
59
+
return ans && validate(root->left,min,root->data) &&
60
+
validate(root->right,root->data,max);
61
+
}
62
+
63
+
64
+
boolisValidBST(Node* root) {
65
+
if(!root)
66
+
returntrue;
67
+
68
+
// calling validate function so that it can check for the left and right subtree .. while giving the range of the values of the nodes.
0 commit comments