我开始在Hackerrank上做一个BST问题,如果树是BST,我应该返回true,否则返回false。在这20宗个案中,我有4宗不及格,我不知道原因何在。造成这个问题的人没有提供关于他/她如何处理输入和如何制作树的详细信息。
这是我的代码:
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));
}
}
}下面是指向hackerrank问题的链接:https://www.hackerrank.com/challenges/ctci-is-binary-search-tree
我在这里做错了什么?
发布于 2017-07-28 14:53:20
子树中的每个节点必须比根小/大。你只要检查子树的根。
例如,这不是BST:
5
3 7
1 6此条件还意味着不存在重复项,您不必单独检查。
https://stackoverflow.com/questions/45376422
复制相似问题