determine if a given binary tree is a valid bst
// Java implementation to check if given Binary tree
// is a BST or not
/* Class containing left and right child of current
node and key value*/
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
// Root of the Binary Tree
Node root;
// To keep tract of previous node in Inorder Traversal
Node prev;
boolean isBST() {
prev = null;
return isBST(root);
}
/* Returns true if given search tree is binary
search tree (efficient version) */
boolean isBST(Node node)
{
// traverse the tree in inorder fashion and
// keep a track of previous node
if (node != null)
{
if (!isBST(node.left))
return false;
// allows only distinct values node
if (prev != null && node.data <= prev.data )
return false;
prev = node;
return isBST(node.right);
}
return true;
}
/* Driver program to test above functions */
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(4);
tree.root.left = new Node(2);
tree.root.right = new Node(5);
tree.root.left.left = new Node(1);
tree.root.left.right = new Node(3);
if (tree.isBST())
System.out.println("IS BST");
else
System.out.println("Not a BST");
}
}
Also in Java:
- getordefault java
- esponente in java
- what is java
- how to make array of objects in java and use it
- How to find the length of an array in java
- bubble sort in java
- string replace java
- java thread
- java min function
- java random seed
- make a commet in java
- java string to uuid
- hashmaps java
- how to detect device javascirpt
- enhanced for loop java
- how to replace all of one character with nothing in java
- java initialize array in one line
- java how to define a function
- convert java list to array
- android studio java random number generator
- java loop
- Enums injava
- Write a JAVA method that expands a given binomial (ax + by)n, where integers a, b, n are user inputs. For example, if a = 2, b = -12, n = 4 are entered the method should print or return
- org.mapstruct maven dependency