The problem is I need to write a function to validate whether a binary tree is a valid binary search tree
This is my code:
public static boolean betterValidBSTArray(TreeNode node) {
WrapInt lastData = null;
return validate(lastData, node);
}
private static boolean validate(WrapInt lastData, TreeNode node) {
if(node == null) return true;
if(!validate(lastData, node.getLeft())) return false;
if(lastData != null && node.getData() <= lastData.value) return false;
if(lastData == null) lastData = new WrapInt();
lastData.value = node.getData();
if(!validate(lastData, node.getRight())) return false;
return true;
}
class WrapInt { int value; }
The problem is, this algorithm is not working. I put some break points and figure out that for each stack call, after lastData gets assigned to a value after the stack call finishes, the previous stack call will continue with lastData = null, even lastData has real value for the previous stack call.
Thank you for any help.