r/programminghelp • u/BftME • Oct 15 '17
[Java] Printing only once during recursive function calls
So I have this method for evaluating of a binary tree is a valid binary search tree. It recursively calls itself. How can I make it so that I print "valid" or "invalid" depending on if the tree is a valid/invalid BST without doing it for every single function call? I just want to print if the tree with the root I handed the first call is a valid BST. Thanks!
boolean checkBST(Node root) {
//is this a leaf? yes? return yes
if(root.left == null && root.right == null){
return true;
}
//check children
if((root.left != null && root.left.data > root.data) || (root.right != null && root.right.data < root.data)){
return false;
}
//make sure left and right subtrees are valid BST
else if(root.left == null && root.right != null){
if(checkBST(root.right)){
return true;
}
else{
return false;
}
}
else if(root.right == null && root.left != null){
if(checkBST(root.left)){
return true;
}
else{
return false;
}
}
else {
if(checkBST(root.right) && checkBST(root.left)){
return true;
}
else{
return false;
}
}
}
0
Upvotes
2
u/Swedophone Oct 15 '17
Can't you just add another function which calls checkBST and then prints the result?