Java 二叉搜索树:插入错误答案
我试图编写二进制搜索插入方法,但它给出了错误的答案。我找不到原因。这是我的密码:Java 二叉搜索树:插入错误答案,java,data-structures,Java,Data Structures,我试图编写二进制搜索插入方法,但它给出了错误的答案。我找不到原因。这是我的密码: public static Node insert(Node root,int data) { Node insertedNode = new Node(data); if(root == null){ root=insertedNode; } else { Node node = root; Node
public static Node insert(Node root,int data) {
Node insertedNode = new Node(data);
if(root == null){
root=insertedNode;
}
else {
Node node = root;
Node insertedNode = new Node(data);
while(root.left !=null && root.right !=null){
if(root.left.data>data){
root=root.left;
}
else {
root=root.right;
}
}
if (data > root.data) {
root.left = insertedNode;
}
else {
root.right=insertedNode;
}
}
}
这个问题很容易发现。查看您的
,同时查看:
while(root.left !=null && root.right !=null){
if(root.left.data>data){
root=root.left;
}
else {
root=root.right;
}
}
只有当根的左右两侧都存在时,它才会寻求更深的层次。那么,假设您尝试添加2,3,4。您插入2,它将成为您的根。然后,尝试添加3。您的while检测到根的左和右都不为null是不正确的。因此,它将在右侧添加3。到目前为止,一切顺利:
2
\
3
现在,您尝试添加4。while检查root.left和root.right是否为空。它是假的,所以它将是根的右边,导致
2
\
4
而不是
2
\
3
\
4
让我们修复您的while:
while((root != null) && (((root.data < data) && (root.left != null)) || ((root.data > data) && (root.right != null)))){
if(root.left.data>data){
root=root.left;
}
else {
root=root.right;
}
}
while((root!=null)&&((root.datadata)&&&(root.right!=null))){
if(root.left.data>data){
root=root.left;
}
否则{
root=root.right;
}
}
而循环是问题的起点。考虑一下while
循环将如何针对示例输入执行。您说您在输入时得到了错误的答案。那个答案是什么?我在黑客级别上解决它,我只是简单地返回树的头节点。我只是想知道关于算法的逻辑是否有错误。正如@Yousaf所说的,试着用你的头脑或论文,一些示例输入。第一个输入:10,它成为根。第二次输入5,它变成root.left。第三次输入3时,它删除5并将自身添加为root.left以代替5。