簡體   English   中英

找到二叉搜索樹的最佳根

[英]Find the best root for Binary Search Tree

我正在嘗試為我的二叉搜索樹找到最好的根。 即這是我的二叉搜索樹。

         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;
}

由於您從排序的數字開始,找到根節點非常簡單:理想的根是要插入的數字的中位數。

這使得遞歸插入變得相當簡單:找到中位數,將其作為根插入,然后將左子數組作為左子數組插入,將右子數組作為右子數組插入。

有一個類似的問題和一個算法,看起來就像這里要求的那樣:

  1. 使用右旋操作,將樹變成鏈表(又名骨干或藤蔓)
  2. 圍繞其父節點旋轉主干的第二個節點,將主干變成完美平衡的 BST。

http://www.geekviewpoint.com/java/bst/dsw_algorithm

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM