2016-05-09 3 views
2

私はバイナリツリーの新機能で、シンプルなゲームのための追加メソッドを扱っています。現在、このメソッドは、新しいノードを追加するたびにルートノードの子ノードを置き換えます。ルートノードの最初の2つの子ノードを置き換えるのではなく、ツリー全体に新しいノードを追加するにはどうすればよいですか?これはこれまで私が持っているものです:最初の2つの子ノードを超えてノードを追加するには、どのようにしてBSTの追加メソッドを取得できますか?

public boolean add(User friend) { 
    User node = friend; 
    if (root == null) { 
     root = node; 
     return true; 
    } 
    if (node.key() < root.key()) { 
     if(root.left == null) { 
      root.setLeft(node); 
     } 
    } else if (node.key() > root.key()) { 
     if(root.getRight() == null) { 
      root.setRight(node); 
     } 
    } 
    return true; 
} 
+1

[こちら](http://algorithms.tutorialhorizo​​n.com/binary-search-tree-complete-implementation/)を参考にしてください。 –

+0

このツリーは 'User'クラスの一部であるようです。別の 'BinarySearchTree 'クラスを作成し、 'User'クラスに' private BinarySearchTree friends'フィールドを持たせるほうがよいでしょう。 'User :: beFriend'は単に' friends.add'を呼び出します。 – Oebele

+0

@ VladK。そのガイドはよく木を説明します。 – girthquake

答えて

1

通常、バイナリツリーでは、再帰関数を記述します。ある関数呼び出しから挿入を管理する代わりに、ノードが属する側を見つけてそのノード側の再帰関数呼び出しに挿入を渡すことができます。

この関数がクラスUserに属していると仮定すると、これはうまくいくはずです。

public boolean beFriend(User friend) { 
    User node = friend; 
    if (root == null) { 
     root = node; 
     return true; 
    } 
    if (node.getKey() < root.getKey()) { 
     if(root.getLeft() == null) { 
      root.setLeft(node); 
     } else { 
      // recursively call beFriend handing insertion to the child 
      root.getLeft().beFriend(node); 
     } 
    } else if (node.getKey() > root.getKey()) { 
     if(root.getRight() == null) { 
      root.setRight(node); 
     } else { 
      // recursively call beFriend handing insertion to the child 
      root.getRight().beFriend(node); 
     } 
    } else { // node.getKey() == root.getKey() so we replace the previous root 
     node.setLeft(root.getLeft()); 
     node.setRight(root.getRight()); 
     root = node; 
    } 
    return true; 
} 
+0

キーが同じであれば、それを置き換えるのではなく、なぜ置き換えるのですか?これはあなたの答えから見逃されているように思われます。 – Oebele

+0

鍵がどこでどのように生成されているのかわからないので、私には安全な賭けのように思えました。最悪の場合、我々は少し余分な仕事をしました。最良の場合、それは、所望のユーザで正しく更新される。 –

+0

申し訳ありませんが、どのクラスに属しているかを記述しておく必要があります。独自のBinaryTreeクラスと、 'getKey()'キーを保持するUserクラスの分離クラスがあります。 – girthquake

関連する問題