恥ずかしすぎて聞けない、痛々しいほど愚かな質問。私は過去4時間検索し、さまざまなアルゴリズムをテストし、紙でかなりの数を試しましたが、それでも機能させることができません。
プロジェクトの実装の詳細は割愛しますが、基本的な質問は次のとおりです。「プレオーダーバイナリツリーへのノードの挿入をどのように処理しますか。
事前注文BSTとは、すべてのノードをそのような方法で挿入する必要があることを意味します。つまり、事前注文トラバーサル(印刷など)を使用してツリーをトラバースすると、ノードが昇順で印刷されます。
必要なのは単純なアルゴリズムだけです。私はここで与えられた単純な挿入アルゴリズムを試しました(stackoverflowで、しかしそれは正しくないようです(紙でも試しました));。
ノードは基本的に次のようなものです。
typedef struct testNode{
int key;
struct testNode *leftChild;
struct testNode *rightChild;
}NODE;
挿入データは、一意の整数の単なるリストです。intをキーとしてノードを作成し、そのノードをツリーに追加する必要があります。私はルートノードを持っています。これはNULLポインターとして始まります。
不明な点がある場合は申し訳ありません。
助けてくれてありがとう!
編集:以下に提供されるアルゴリズムに基づいて、これは私が思いついたものです:
void insert(NODE **tree,int key){
if(*tree){
if ((*tree)->key >= key){
//Insert before this .....
NODE *temp = createNode(key);
temp->lc = (*tree);
(*tree) = temp;
}
else if(!(*tree)->rc){
//Right Child doesn't exist ....
insert(&(*tree)->lc,key);
}
else if((*tree)->rc->key < key){
//Right child exists and is smaller than spread ... insert left ...
insert(&(*tree)->lc,key);
}
else{
//Right child exists and is greater than spread ... insert right ...
insert(&(*tree)->rc,key);
}
//If the code as progressed to this point, insertion must have occured,
//and the code returns ......
} else {
//the **tree pointer points to NULL. Insert here ....
SPREADNODE *temp = createSpreadNode(spread);
//temp->lc = (*tree);
(*tree) = temp;
}
}