【发布时间】:2017-05-08 09:29:14
【问题描述】:
这种递归顺序遍历方法有些麻烦 我的代码应该按顺序遍历给定的树,如果正确执行则返回 true。我通过遍历它并将元素添加到 arrayList 来做到这一点。我有一个 isSorted 方法,如果数组列表已排序(每次添加数组列表元素时都会完成),则返回 1,否则返回 0。
它的工作是返回对应于它是否已排序的 correcy 1 或 0,但之后它不会停止执行。因为如果它没有排序,那么可以肯定地说顺序遍历没有正确完成,但它说它是正确的。有人可以帮忙吗?
public ArrayList<Integer> inOrderCheck = new ArrayList<Integer>();
boolean checkBST(Node root) {
if(root != null){
checkBST(root.left);
if(addToList(root.data) == 0){
return false;
}
checkBST(root.right);
}
return true;
// Integer[] inOrderArray = inOrderCheck.toArray(new Integer[inOrderCheck.size()]);
}
int addToList(int data){
//System.out.println("Initial size of inOrderCheck: " + inOrderCheck.size());
if(!(inOrderCheck.contains(data))){
// System.out.println("Adding: " + data);
inOrderCheck.add(data);
}
//System.out.println(" size of inOrderCheck after adddition: " + inOrderCheck.size());
// System.out.println("Contents of inOrderCheck: " + inOrderCheck);
// System.out.println("Result of isSorted: " + isSorted());
return isSorted();
}
int isSorted(){
int sorted = 0;
for (int i = 1; i < inOrderCheck.size(); i++) {
//System.out.println("Result of isSorted: " + inOrderCheck.get(i-1) + " "+ inOrderCheck.get(i));
if (inOrderCheck.get(i-1) < (inOrderCheck.get(i)) ) {
sorted = 1;
}else
sorted = 0;
}
return sorted;
}
【问题讨论】:
-
也许您不应该忽略从对
checkBST的递归调用返回的布尔值。 -
@Eran 喜欢什么将它们设置为布尔值?
-
@SJackson193 如果
checkBST(root.left)返回 false,您应该返回 false。checkBST(root.right)也一样。
标签: java algorithm binary-search-tree inorder