【问题标题】:Binary Search Tree insertion error二叉搜索树插入错误
【发布时间】:2016-12-04 13:35:09
【问题描述】:
package array;

import java.util.Scanner;

class node<T>{
    T data;
    node<T> left;
    node<T> right;
}
public class binarytree {

    public static void main(String [] args){
    node<Integer> root = null;
    node<Integer> n = new node<>();
    Scanner s = new Scanner(System.in);
    root=create(s.nextInt());
    System.out.println("root creates");
    //root=insert(n,root);
    for(int i =1;i<6;i++){
        n=create(s.nextInt());
        insert(n,root);
        System.out.println(i+"th inserted ");
        inorder(root);
        System.out.println();
    }
    }
    private static void inorder(node<Integer> root) {
        if(root==null){
            return;
        }
        inorder(root.left);
        System.out.print(root.data+" ");
        inorder(root.right);
        return;
    }
    private static void insert(node<Integer> n, node<Integer> root) {
        if(root.left==null&&root.right==null){//line 37
            if(root.data>n.data){
                root.left=n;
            }
            else{
                root.right=n;
            }

        }
        else if(root.data>n.data){
            insert(n, root.left);//line 47
        }
        else{
            insert(n, root.right);
        }

        return ;
    }
    private static node<Integer> create(int data) {
        node<Integer> n = new node<>();
        n.data=data;
        n.left=n.right=null;
        return n;
    }
}

该代码适用于正小整数,但在某些输入时会出现空指针异常,例如:

2 -3 1 -44 

它停止并给出空指针异常。

不过有一些这样的,它工作得很好

6 4 3 2 1 

堆栈跟踪:

Exception in thread "main" java.lang.NullPointerException
    at array.binarytree.insert(binarytree.java:37)
    at array.binarytree.insert(binarytree.java:47)
    at array.binarytree.insert(binarytree.java:47)
    at array.binarytree.main(binarytree.java:21)

【问题讨论】:

  • 你能把你的堆栈跟踪并指出它在哪一行失败吗?
  • 您是否考虑过root 为空时会发生什么?

标签: java nullpointerexception binary-search-tree insertion


【解决方案1】:

root.left == null 为 false 并允许 root.right 失败时,插入中的 if 语句是短路的,然后您在递归中传递 root.right,它为空。或者你的树是空的,根是空的。

尝试像这样重组

private static void insert(node<Integer> n, node<Integer> root) {
    if (n == null) return;
    if (root == null) {
       // TODO: Set the root? 
    }  

    Integer data = n.data;
    Integer rootData = root.data;

    if (data < rootData) {
        if(root.left == null){
            root.left = n;
        }
        else{
            insert(n, root.left);
        }
    }
    else if(data >= rootData){
        if (root.right == null) {
            root.right = n;
        } else {
            insert(n, root.right);
        }   
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多