二叉搜索树:插入错误答案

问题描述

我正在尝试编写二进制搜索插入方法,但它给出了错误的答案。我找不到是什么原因。这是我的代码

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

    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 检测到 root 的左侧和右侧都不为空。因此,它将在右侧添加 3。到目前为止,一切都很好:

2
  \
     3

现在,您尝试添加 4。您的 while 检查 root.left 和 root.right 是否不为空。是假的,所以会是root的右边,导致

2
  \
     4

代替

2
  \
     3
       \
         4

让我们解决您的问题:

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;
     }
}