the problem need write function validate whether binary tree valid binary search tree
this 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, algorithm not working. put break points , figure out each stack call, after lastdata gets assigned value after stack call finishes, previous stack call continue lastdata = null, lastdata has real value previous stack call.
thank help.
to fix code should not if(lastdata == null) lastdata = new wrapint(); assigns reference new object method call parameter local variable each stack call, , should pass not null lastdata object used across whole recursion, changing value.
Comments
Post a Comment