【发布时间】:2020-09-22 05:04:17
【问题描述】:
我只是根据逻辑自己实现了二叉搜索树插入方法。 那么,任何人都可以在插入和搜索时验证代码是否正常工作(使用您自己的搜索方法,如 inorder、preorder、postorder)?
并且还要求代码的时间复杂度。
public void insert(int data) {
Node node = new Node(data);
if (root == null) {
root = node;
size++;
} else {
Node n = root;
if (data > n.data) {
while (n.right != null) {
n = n.right;
}
if (data < n.data) {
while (n.left != null) {
n = n.left;
}
if (data != n.data) {
n.left = node;
size++;
}
} else {
if (data != n.data) {
n.right = node;
size++;
}
}
} else if (data < n.data) {
while (n.left != null) {
n = n.left;
}
if (data > n.data) {
while (n.right != null) {
n = n.right;
}
if (data != n.data) {
n.right = node;
size++;
}
} else {
if (data != n.data) {
n.left = node;
size++;
}
}
}
}
}
编辑:- 我在插入这些数字时发现了一个问题:-
bst.insert(10);
bst.insert(11);
bst.insert(90);
bst.insert(13);
bst.insert(12);
bst.insert(70);
bst.insert(80);
它会这样打印(按顺序):- 10 11 80 70 12 13 90
【问题讨论】:
标签: java data-structures binary-search-tree