繁体   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