-2

I wrote a function to build a BTS from a unsorted array

public static TreeNode buildTree(int[] a){
    TreeNode parent=new TreeNode();
    TreeNode curr=new TreeNode();
    curr.e=a[0];
    TreeNode root=curr;
    int v;
    for(int i=1;i<a.length;i++){
        curr=root;
        v=a[i];
        A: while(curr!=null){
            if(v>=curr.e) {
                parent=curr;
                if(curr.right==null) break A;
                    curr=curr.right;
            }
            else{
                parent=curr;
                if(curr.left==null) break A;
                curr=curr.left;
            }
        }
        //parent is leaf
        if(v>=parent.e){
            System.out.println(parent.e);
            parent.right=new TreeNode();
            parent.right.e=v;
        }
        else{
            parent.left=new TreeNode();
            parent.left.e=v;
        }
    }
    return root;
}

If I didn't add these lines:

if(curr.left==null) break A;
if(curr.right==null) break A;

I got nullPointerException.

I don't understand why. When curr.left is null, then I assign curr=curr.left, isn't I make curr=null, than the while loop will be break?

Is it illegal to assign null to a object like this?

Thanks!!

Baby
  • 5,062
  • 3
  • 30
  • 52
fuiiii
  • 1,359
  • 3
  • 17
  • 33

2 Answers2

0

Oh... Sorry!!!

It works, the reason it didn't work before was I forgot the add else{} around

parent=curr;
    if(curr.left==null) break A;
        curr=curr.left;

That's why I had nullPointerException.

if(curr.left==null) break A;
if(curr.right==null) break A;

Are unnecessary.

fuiiii
  • 1,359
  • 3
  • 17
  • 33
  • I have to wait for two days to accept my own answer. And I couldn't delete it since it has been answered. – fuiiii Jan 11 '14 at 03:12
0

The Application without exception when i Commented these lines:if(curr.left==null) break A; if(curr.right==null) break A; my Code is buildTree(new int[]{1,0,1}); and result is 1,no error。Can you provide more detailed information

  • sorry, you're right. The code works find without (if(curr.left==null) break A; if(curr.right==null) break A;). See my answer below. – fuiiii Jan 11 '14 at 03:28