I have to return true or false if an input String is a valid or not valid BST(Binary Search Tree).
The problem is that i have in input an atypical string with this "pattern" : ( ROOT (LEFT , RIGHT ) ); there is a space between every element, ROOT is the central node, LEFT the left one and RIGHT the right one. If a node is null is encoded like "-",a leaf is encoded with the numeric value, if a node have some child is encode in this way: For example B have two child (D at left,E at right) so ( A ( B ( D , E ) , C ) )
I have tried to split the string in an array of String but i have no idea how to populate the tree and at the same time check if it is a BST.How i can populate the tree with this String?
I would try with this algorithm:
//How i split the String
String[] albero = b.readLine().split("\\,|\\(|\\)|\\-");
//How i would check if is a BST
public class IsBST {
public boolean isBST(Node root){
return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
private boolean isBST(Node root, int min, int max){
if(root == null){
return true;
}
if(root.data <= min || root.data > max){
return false;
}
return isBST(root.left, min, root.data) && isBST(root.right, root.data, max);
}
Example:
INPUT 1: ( 100 ( 19 ( 17 ( 2 , 7 ) , 3 ) , 36 ( 25 , 1 ) ) )
OUTPUT 1: false
INPUT 2: ( 8 ( 3 ( 1 , 6 ( 4 , 7 ) ) , 10 ( - , 14 ( 13 , - ) ) ) )
OUTPUT 2: true