私のバイナリ検索ツリーに最適なルートを見つけようとしています。つまりこれは私のバイナリ検索ツリーです。バイナリ検索ツリーに最適なルートを探します。
42
/ \
/ \
25 53
/\ /\
23 41 49 55
/\/\/\/\
次に、それらをinOrder walkの形式で配列に保存します。
| 23 | 25 | 41 | 42 | 49 | 53 | 55 | .........
........... ↑ ........... ↑ ........... ↑。 ..........
だから、矢印を指しているのは、どれが最良のルート41,42,53であるかを調べるノードです(アレイは大きくて病気になります配列の奇数インデックスとツリーの所与の深さ)。私は木がすでにバランスであるかもしれないことを知っていますが、これは実験ですので、私と一緒に裸にしてください。
私は新しいルートとしてすべての単一の奇数インデックスを試して、前のものとそれぞれの高さを比較し、どのようなものが私の最高の高さであるかを判断できるようにしなければなりません。私は25を決定した場合、すなわち、私は各ので、この
25 25
\ \
\ \
42 or 53
\ /
53 42
\ /
のようなツリーを持つことができ、私の新しいルートである私がチェックし、配列内の前のノードとの高さを比較して、私はそれが私に与えるノードを返します最良のノード。 は、これまでのところ、私はこれを試してみました:
void rebalance(){
//this is the size for the array and NumDepth is defined at the constructor
int size = (pow (2,(numDepth +1))-1);
Node* Array2 [size];
int i = 0;
int bestH = 0;
Node* temp;
for (int i=0; i < size; i++){
Array2[i]= new Node();
Array2[i]= NULL;
}
//this function will be the one creates the inOrder walk and saves my nodes inside the array
storeInOrder(rootBST, Array2, i, numDepth);
temp = shortestBST(Array, rootBST, bestH, height);
}
Node* shortestBST(Node *root[], Node* root, int &bestHeigth, int sizeA) {
//root is my main tree basically
//this is how i know that i have to use the odd numbers in the array
for(int i= 1; i< sizeA; i+=2){
//inside here I am supposed to do a recursion to check every node inside the array to check the node that is the best
//they gave me a hint saying that i can point the nodes in the array to the ones in my main tree to create the tree with the new testing root in order to check if that node can create a best tree but i don't know how to do that using recursion
//each of my nodes hold a key, a height and a size of a subtree , left to point to the left and a right to point to the right
}
}
Node::Node() {
sizeSub=0;
height=1;
key=0;
left=NULL;
right=NULL;
}
私はrootとして各奇数インデックスを試し「しなければならない」理由について困惑しています。あなたがこれを行う必要があるといういくつかの要件がありますか?なぜあなたは根を考慮していないのですか? – templatetypedef
ええ、奇妙なインデックスだけを試す必要がある、彼らはそれをシングルトンと呼びます。あなたが私にしたいなら、私はもっと説明することができます。 – Bryan
@ブライアン 'intサイズ=(pow(2、(numDepth +1))-1); Node * Array2 [size]; ' - これらの2行のコードには、少なくとも2つのことが間違っているか、危険です。整数指数で使用されたときの最初の 'pow'は、正しい結果を得ることが保証されていません。 [これを見てください](https://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os/25678721#25678721)。 2番目の 'Node * Array2 [size]'は正当なC++構文ではありません。なぜなら配列はエントリの数を表す定数を使って宣言しなければならないからです。 – PaulMcKenzie