2012-10-07 38 views
1

我已经编写了一个代码,用于向二叉树插入一个元素的泛型类型,它是按其名称排序的。不要认为这是正确的。java二叉树插入函数非递归

public boolean insert(E e) { 
    BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
    } 
    while (temp != null) 
    if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
     temp = temp.getRight(); 
    } else { 
     temp = temp.getLeft(); 
    } 
    temp.setElement(e); 
    return true; 
} 

你能建议我更正吗?

+1

问题是什么? – Augusto

+4

在while语句后删除分号。 –

+0

'temp' - 变量名称的绝佳选择。 –

回答

2

一种插件,需要创建一个新的节点。我现在没有如何创建它们,因为我没有看到构造函数,但我建议沿着以下几点:

public boolean insert(E e) {   
    if (root == null) { 
     root = new BTNode(); 
     root.setElement(e); //how would this work with a null root? 
     return true; //that's it, we're done (when is this ever false by the way?) 
    } 
    BTNode current = root; 
    while (true) { //brackets! indenting is important for readabilty 
     BTNode parent=current; 
     if (current.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      current = current.getRight(); 
      if(current==null) { //we don't have a right node, need to make one 
       current = new BTNode(); 
       parent.setRight(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } else { 
      current= current.getLeft(); 
      if(current==null) { //we don't have a left node, need to make one 
       current = new BTNode(); 
       parent.setLeft(current); 
       break; //we have a new node in "current" that is empty 
      } 
     } 
    } 
    current.setElement(e); 
    return true; 
} 
-1

随着艾玛迪斯提到的,while循环不应该有一个分号结尾:

BTNode temp = root; 
    if (root == null) { 
     root.setElement(e); 
     return; 
    } 
    while (temp != null) 
    { 
     if (temp.element().getClass().getName().compareTo(e.getClass().getName()) < 0) { 
      if(temp.getRight() != null) 
      temp = temp.getRight(); 
      else 
      { 
       temp.createRight(e); 
       temp = null; //or break 
      } 
     } else { 
      if(temp.getLeft() != null) 
      temp = temp.getLeft(); 
      else 
      { 
       temp.createLeft(e); 
       temp = null; //or break 
      } 
     } 
    } 

    return true; 
+0

-1和正如我所说:然后行temp.setElement(e);总是空指针异常。 – weston

+0

另一种解决方案是捕捉异常并处理'catch'块中的节点创建......虽然很丑陋...... –

+0

仍然错误'temp = null;'那么这将如何阻止NPE? – weston