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
+
#include<bits/stdc++.h>
28
+
usingnamespacestd;
29
+
30
+
structNode {
31
+
int data;
32
+
structNode *left, *right;
33
+
34
+
Node(int data)
35
+
{
36
+
this->data = data;
37
+
left = right = NULL;
38
+
}
39
+
};
40
+
41
+
42
+
boolvalidate(Node* root,longlongint min , longlongint max){
43
+
if(!root)
44
+
returntrue;
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) &&
0 commit comments