algorithm - Code for checking if a tree is a Binary Search Tree in Java is failing test cases. Unsure why -
i began doing bst problem on hackerrank, should return true if tree is bst, , false otherwise. failing 4 out of 20 total cases , not sure why. person made problem did not provide detail information on how he/she handles inputs , makes tree.
here code:
map<integer, integer> nummap = new hashmap<integer, integer>(); boolean checkduplicates(int val){ if(nummap.containskey(val)){ return false; } else{ nummap.put(val, 1); return true; } } boolean checkbst(node root) { if(root.left == null && root.right == null){ return (true && checkduplicates(root.data)); } else if(root.left.data > root.data || root.right.data < root.data){ return false; } else{ if(root.left == null){ return (checkbst(root.right) && checkduplicates(root.data)); } else if(root.right == null){ return (checkbst(root.left) && checkduplicates(root.data)); } else{ return (checkbst(root.left) && checkbst(root.right) && checkduplicates(root.data)); } } }
here link hackerrank problem: https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
what doing wrong/overlooking here?
every node in subtree must smaller/larger root. check root of subtree.
for example not bst:
5 3 7 1 6
this condition implies there no duplicates, don't have check separately.
Comments
Post a Comment