私はしばらくの間、バイナリ ツリーを装ったこのグラフを動作させようと試みてきました。現在、ルート ノードと探しているノードの ID を渡す関数を使用しています。唯一の問題は、コーディング方法によっては、一方の側が 3 ノードを超えることができないことです。私は再帰を正しく行っていないと確信しています。私はこれに一晩中立ち往生しており、これを取得できません。他のグラフやツリーを調べてみましたが、役に立ちませんでした。実際の頂点やその他のグラフのようなプロパティは使用if (x <root.getID())
していませんが、root.left をそのまま使用することはできません。
これは、いくつかのノードを長くすると、右側で機能しなくなる私の非機能検索アルゴリズムです。Visited は HashSet() クラスを使用しています。
private Node dfs(Node x, int id)
{
if (x==null) //base case. Runs into null link
return null;
if(visited.contains(x.getID())) //visited before
return null;
visited.add(x.getID()); //don't go below Node again
if(id==x.getID())
return x;
Node rc = dfs(x.getRightChild(), id);
Node lc = dfs(x.getLeftChild(), id);
//recursive calls
if (lc.getID()==id)
return lc;
if(rc.getID()==id)
return rc;
return null;
}
すべてのツリーを印刷するための作業コードがありますが、上記のコードのキー比較のためにコードを変更することはできません。
private String dfsPrint(Node x) //pass in root at top level
//returns a String containing all ID's
{
if (x==null) //base case. Runs into null link
return "";
if(visited.contains(x.getID())) //visited before
return "";
visited.add(x.getID()); //don't go below Node again
String lc = dfsPrint(x.getLeftChild()); //recursive stuffs
String rc = dfsPrint(x.getRightChild());
return Integer.toString(x.getID()) + " " + lc + rc;
}
助けてくれてありがとう。
編集:私がやっていることを拡張すると思います。新しいノードを配置する関数 makeRight または makeLeft が必要です。その後、既存のノードがその左または右の子を配置します。これがそれです。その検索には、プライベート dfs を呼び出すパブリック メソッドがあります。
Node search(int id) // calls private dfsSearch() returns null or a ref to
// a node with ID = id
{
int ID = id;
Node x= dfs(root, ID);
return x;
}
void ML(int x, int y) // ML command
{
visited.clear();
Node temp = new Node(y, null, null);
Node current = search(x);
current.putLeft(temp);
}
void MR(int x, int y)//MR command
{
visited.clear();
Node temp = new Node(y, null, null);
Node current = search(x);
current.putRight(temp);
}
lc と rc の if ステートメントの再帰関数をどのように並べるかによって、ツリーの別の側が基本ケースに再帰されます。これが、dfs メソッドが間違っていると思い込ませる理由です。要求されたノード クラスは次のとおりです。
class Node {
private int ID; //ID of the Node. Distinct
private Node leftChild;
private Node rightChild;
Node(int identification)//constructor
{
ID = identification;
}
Node(int identification, Node lt, Node rt) //constructor
{
ID = identification;
leftChild = lt;
rightChild = rt;
}
int getID()
{
return ID;
}
Node getLeftChild()
{
return leftChild;
}
Node getRightChild()
{
return rightChild;
}
void putLeft(Node lt)
{
leftChild = lt;
}
void putRight (Node rt)
{
rightChild = rt;
}
}