为二叉树构造一个无递归插入方法

时间:2015-12-09 02:49:11

标签: java non-recursive

我已经完成了递归插入函数并且它工作得很好,但我无法使非递归解决方案起作用。

public void insert(T item){
root= nonRecursive(root,item);
}
public BinaryTreeNode<T> nonRecursive(BinaryTreeNode<T> tree, T item){

if(root==null){
  root=new BinaryTreeNode<T>(item);
  return root;
}
else{
 BinaryTreeNode<T> next = new BinaryTreeNode<T>();
 Comparable<T> temp = (Comparable<T>) root.info;
  if(temp.compareTo(item)== 0){
   return null;
  }
  else if(temp.compareTo(item) > 0){
    next=root.lLink;
  }
  else{
   next=root.rLink; 
  }
  while(next != null){
    Comparable<T> temp2 = (Comparable<T>) next.info;
    if(temp.compareTo(item) == 0){
      return null;
    }
    else if(temp2.compareTo(item) > 0){
     next=next.lLink; 
    }
    else{
     next=next.rLink; 
    }

  }
  next=new BinaryTreeNode<T>(item);
  return root;
}

} 然后递归的是:

public void insert(T item) {
  root = recInsert(root, item);
}
public BinaryTreeNode<T> recInsert(BinaryTreeNode<T> tree, T item) {
  if(tree == null) {
 //create new node
    tree = new BinaryTreeNode<T>(item);
  }
  else {
    Comparable<T> temp = (Comparable<T>) tree.info;
    if (temp.compareTo(item) == 0) {
      System.err.print("Already in ­ duplicates are not allowed.");
      return null;
    }
    else if (temp.compareTo(item) > 0)
      tree.lLink = recInsert(tree.lLink, item);
    else
      tree.rLink = recInsert(tree.rLink, item);
  }
  return tree;
}

有谁知道我做错了什么? 我以为我已经得到了它,但现在它只返回我输入的第一个数字

2 个答案:

答案 0 :(得分:0)

这里你去吧

在你的代码中,

if(current == null){
    current.lLink=node;

如果current为null,那么它怎么能有iLink

也许你需要做

if(current == null){
    current = new Node ();
    current.lLink=node;

答案 1 :(得分:0)

您的代码甚至还没有完成。

你甚至没做过一次比较。你所做的只是毫无意义的循环。

如果您正在寻找非递归逻辑,这里是伪代码。你的工作就是理解它并用Java编写。

insert(item) {
    Node itemNode = new Node(item);

    if root is null {
        root = itemNode
        return
    }

    currentNode = root;

    keep looping until node is inserted {
        if currentNode is equals to itemNode {
            show error and exit
        } else if itemNode is smaller than currentNode {
            if (currentNode has no left){
                set currentNode's left to itemNode
                // Item Inserted!!!!
            } else {  // there are node at currentNode's left
                 set currentNode to currentNode's left (and continue lookup)
            }
        } else { // item node is greater than current node
             // do similar thing as the "itemNode < currentNode logic", 
             // of course on currentNode's right
        }
    }
}