Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- boolean checkBST(Node root) {
- boolean leftflag = false;
- boolean rightflag = false;
- Node l = root.left;
- Node r = root.right;
- if(l!=null) {
- if(root.data <= l.data) {
- leftflag = false;
- }
- else {
- leftflag = true;
- checkBST(l);
- }
- }
- if(leftflag == false)
- return false;
- if(r != null) {
- if(root.data >= r.data) {
- rightflag = false;
- }
- else {
- rightflag = true;
- checkBST(r);
- }
- }
- if(rightflag == false)
- return false;
- return true;
- }
- public boolean isValid(Node root) {
- return isValidBST(root, Integer.MIN_VALUE,
- Integer.MAX_VALUE);
- }
- private boolean isValidBST(Node node, int MIN, int MAX) {
- if(node == null)
- return true;
- if(node.value > MIN
- && node.value < MAX
- && isValidBST(node.left, MIN, node.value)
- && isValidBST(node.right, node.value, MAX))
- return true;
- else
- return false;
- }
- 7
- /
- 3 8
- /
- 4 6 9
- // The condition here is respected, there is no left node
- // But the tree is an actual search tree, you didn't check right node
- // Before returning false.
- if(leftflag == false)
- return false
- if(l != null)
- {
- if(root.data<=l.data)
- {
- return false;
- }
- else
- {
- // recursive call here
- }
- }
- if(r != null)
- {
- // Same as left node here
- }
- else {
- leftflag = true;
- checkBST(l);
- }
- }
- if(leftflag == false)
- return false;
- else
- leftflag = checkBST(l)
- if (flag == false)
- if (!flag)
- if (l)
- boolean leftflag = false;
- boolean rightflag = false;
- if(l) {
- if(root.data > l.data) {
- leftflag = checkBST(l);
- }
- }
- if(!leftflag)
- return false;
- if(r) {
- if(root.data < r.data) {
- rightflag = checkBST(r);
- }
- }
- if(rightflag == false)
- return false;
- return true;
- }
- return
- (!root.left || // Is left subtree a BST?
- (root.data > root.left.data &&
- checkBST(root.left)))
- &&
- (!root.right || // Is right subtree a BST?
- (root.data > root.right.data &&
- checkBST(root.right)))
Add Comment
Please, Sign In to add comment