0

再帰挿入機能を完成させましたが、完全に機能しますが、非再帰ソリューションを機能させることができません。

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

誰かが私が間違っていることを知っていますか? 私はそれを手に入れたと思ったが、今は最初に入力した数字しか返さない

4

2 に答える 2

0

どうぞどうぞ

あなたのコードで、

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

current が null の場合、どのようにして ? を持つことができますiLinkか?

多分あなたはする必要があります

if(current == null){
    current = new Node ();
    current.lLink=node;
于 2015-12-09T02:56:18.690 に答える
0

あなたのコードは完成に近づいていません。

あなたは1回も比較をしていません。あなたがしたことは、単に無意味なループです。

非再帰的なロジックを探している場合は、ここに疑似コードがあります。あなたの仕事は、それを理解し、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
        }
    }
}
于 2015-12-09T03:15:19.090 に答える