如何解决这是有效的BST插入吗?
我仅基于逻辑就实现了二进制搜索树插入方法。 那么,有人可以在插入和搜索时验证代码是否运行正常(使用您自己的搜索方法,例如顺序,前置,后置)?
并找到代码的时间复杂度。
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
解决方法
您的代码似乎存在一些问题:
if (data > n.data) {
while (n.right != null) {
n = n.right;
.
.
}
}
指的是像这样的树:
10
/ \
8 15
/ \
12 23
\
26
/
20
并要求插入例如21,给定的算法将尝试将其插入到26的左子节点中。但是,此节点已被占用,因此您的算法有缺陷。 我建议您像下面这样递归地从每个节点调用插入:
// in class tree
public void insert(int data) {
if (root == null) {
root = new Node(data);
}
else {
root.insert(data);
}
size++;
}
//in class Node
public void insert(int data) {
if(data>=this.data){
if(right==null) right=new Node(data)
else right.insert(data);
}
else{
if(left==null) left=new Node(data)
else left.insert(data);
}
}
由于每个节点都有责任在插入之前检查其子节点是否为空,因此此问题不再重复。
就复杂性而言: 你会得到像这样的树
1
\
2
\
3
\
...
\
n
在其中插入大于n的值将导致传递n个节点,因此时间复杂度为O(n)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。