【发布时间】:2021-10-27 20:32:12
【问题描述】:
这是我搜索元素的代码是使用 java 的二叉搜索树。 当我执行两次搜索方法时,第二个元素的输出显示为 false。就像树中存在 10 一样,该元素也显示为 false 。 代码太长,只好去掉中序遍历和插入元素方法。
public class BinarySearchTree {
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
Node root;
BinarySearchTree() {
root = null;
}
// search data method
boolean search(int data) {
root = searchData(root, data);
if (root != null) {
return true;
}
return false;
}
Node searchData(Node root, int data) {
if (root == null) {
return null;
}
if (data == root.data) {
return root;
} else if (data < root.data) {
return searchData(root.left, data);
} else {
return searchData(root.right, data);
}
}
public static void main(String[] args) {
BinarySearchTree bst = new BinarySearchTree();
bst.insert(60);
bst.insert(30);
bst.insert(10);
System.out.println("Number found : " + bst.search(60));
System.out.println("Number found : " + bst.search(10));
}
}
上述代码的控制台输出:- 找到的号码:真 找到的号码:假
【问题讨论】:
-
我的回答解决了你的问题吗?能否给点意见。
标签: java tree binary-tree binary-search-tree