0

二分探索木(再帰またはループ)での検索操作のより良い実装はどれですか?

4

5 に答える 5

2

検索する場合、再帰は必要ありません。この状況では、再帰はやり過ぎです。ループを記述して、見つかったときにブレークするか、リーフ ノードでブレークする (見つからない場合)

于 2012-11-20T03:02:12.340 に答える
2

通常、再帰は実装が簡単で、少なくともツリーを使用すると、他の人間にとってコードが読みやすくなります。しかし、最終的には、ツリーのバランスが取れているかどうかによって異なります

  • ツリーのバランスがとれている場合、再帰呼び出しが log(n) を超えないことが保証されているため、確実に再帰を使用できると思います(たとえば、 n=100000000 の場合、実行する必要がある再帰呼び出しの最悪の数は約 27 です)。

  • 一方、ツリーのバランスが取れていない場合は、ツリーのすべての要素をチェックする必要があり、再帰はスタックを維持するために大量のメモリを使用する可能性があるため、ループが最善の策だと思います。

于 2013-02-26T12:17:11.387 に答える
0

While(current != null) 動作します。

public class BST<E extends Comparable<E>> 
  extends AbstractTree<E> {

  protected TreeNode<E> root;

  protected int size = 0;

~ ~ ~ ~

// Returns true if the element is in the tree 
  public boolean search(E e) {
    TreeNode<E> current = root; // Start from the root

    while (current != null) {
      if (e.compareTo(current.element) < 0) {
        current = current.left;
      }
      else if (e.compareTo(current.element) > 0) {
        current = current.right;
      }
      else // element matches current.element
        return true; // Element is found
    }

    return false;
  }
于 2013-04-18T19:54:38.540 に答える
0

どのアルゴリズムが最適かは、解決しようとしている問題のコンテキストによって異なります。これが役立つことを願っています。 http://en.wikipedia.org/wiki/Binary_search_algorithm

于 2014-05-13T08:53:08.497 に答える
0

エンティティ クラス BinaryTreeNode があると仮定すると、バイナリ検索ツリーでノードを検索する非再帰的な実装は次のとおりです。

public static BinaryTreeNode searchBstNode(BinaryTreeNode temp, int data){

    while(true){
        if(temp.getData()==data){
            break;
        }
        if(temp.getData()>data){
            if(temp.getLeft()!=null){
                temp=temp.getLeft();    
            }
            else{
                System.out.println("Data value ="+ data+" not found!");
                return null;
            }   
        }
        if(temp.getData()<data){
            if(temp.getRight()!=null){
                temp=temp.getRight();
            }
            else{
                System.out.println("Data value ="+ data+" not found!");
                return null;
            }

        }
    }
    System.out.println("Data found in the BST");
    return temp;
于 2013-11-23T10:11:54.213 に答える