将数组排序为二叉搜索树

时间:2016-05-14 17:52:33

标签: c++

所以我有以下代码,我在其中创建了一个constuctor,它使用数组初始化二进制搜索树。构造函数传递数组,对其进行排序,并将其转换为二进制函数。在我的主要功能中,我有一个包含不同案例的菜单,可以对二叉搜索树执行不同的操作。我添加了一系列输出语句来确定错误,我认为当我调用root = findMedian(...)时,我的构造函数存在问题。下面我有构造函数,findMedian函数以及在main中调用它的情况。当我在gdb中运行它时程序不断中止。如果有人可以提供帮助,我将非常感谢,谢谢!

//
//custom constructor that takes an array and turns it into a binary search tree
//
TreeType::TreeType( ItemType a[], int len )
{
        //sort array
        bubbleSort( a, len );
        //call recursive function
        int left = 0;
        int right = len - 1;
        cout << "in constructor, setting root." << endl;
        root = findMedian(a,left,right);
}
//function that finds median
TreeNode * TreeType::findMedian ( ItemType a[], int left, int right )
{
        if ( left > right )
                return NULL;

        TreeNode *tree = new TreeNode;
        int mid = (left+right)/2;
        cout << "Creating a treenode" << endl;
        cout << "a[mid} is: " << a[mid] << endl;
        tree -> info = a[mid];

        tree -> left = findMedian( a, left, mid - 1);//recursively call the left subtree
        tree -> right = findMedian(a, mid + 1, right );//recursively call the right subtree


        return tree;
}

//in main
case 'O':

                {
                        cout << "Enter a string: ";
                        cin >> words;
                        TreeType optimalTree( words, strlen(words));
                        optimalTree.Print();
                        cout << endl;
                        break;
                }

//sample run
Enter a string: YHGTRFB
len is: 7
in constructor, setting root.
left is: 0
right is: 6
Creating a treenode
a[mid} is: F
left is: 0
right is: 2
Creating a treenode
a[mid} is: F
left is: 0
right is: 0
Creating a treenode
a[mid} is: F
left is: 0
right is: -1
left is: 1
right is: 0
left is: 2
right is: 2
Creating a treenode
a[mid} is: F
left is: 2
right is: 1
left is: 3
right is: 2
left is: 4
right is: 6
Creating a treenode
a[mid} is: F
left is: 4
right is: 4
Creating a treenode
a[mid} is: F
left is: 4
right is: 3
left is: 5
right is: 4
left is: 6
right is: 6
Creating a treenode
a[mid} is: B
left is: 6
right is: 5
left is: 7
right is: 6
     F
   /   \
   F   F
 /   \   /   \
 F   F   F   B

0 个答案:

没有答案