java二进制树插入函数非递归

时间:2012-10-07 09:18:23

标签: java tree non-recursive

我编写了一个代码,用于在二叉树中插入一个按名称排序的元素泛型类型。不过不认为这是正确的。

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

你能建议我改正吗?

3 个答案:

答案 0 :(得分: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 :(得分:1)

data Rat = Rat {
    attr1 :: Bool
  , attr2 :: String
  }

答案 2 :(得分:-1)

正如amadeus所提到的,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;