騰訊廣研-筆試題(2) 2012-3-27

2.輸入:一個有序數組和數組大小

   輸出:一個有序二叉樹(二叉查找樹又叫二叉排序樹)它只是說是有序二叉樹沒有說是平衡的,當且當做是平衡的吧!

#include <iostream>
using namespace std;
struct BTreeNode{
    int val;
    struct BTreeNode *left;
    struct BTreeNode *right;
};
void Convert(int array[],int arraysize,struct BTreeNode **root)
{
    if(arraysize==0)
        return;
    if(arraysize==1)
    {
        *root=(struct BTreeNode*)malloc(sizeof(struct BTreeNode));
        (*root)->val=array[0];
        cout<<(*root)->val<<endl;
        (*root)->left=NULL;
        (*root)->right=NULL;
        return;
    }
    int mid=arraysize/2;
    *root=(struct BTreeNode*)malloc(sizeof(struct BTreeNode));
    (*root)->val=array[mid];
    cout<<(*root)->val<<endl;
    Convert(array,mid,&(*root)->left);
    Convert(array+mid+1,arraysize-mid-1,&(*root)->right);
}
void printTree(struct BTreeNode *root)
{
    if(root!=NULL)
    {
        printTree(root->left);
        cout<<root->val;
        printTree(root->right);
    }
}
int main()
{
    int array[]={1,2,3,4,5,6,7};
    struct BTreeNode *root;
    Convert(array,7,&root);
    printTree(root);
    cout<<endl;
    return 0;
}

輸出結果爲:

4
2
1
3
6
5
7
1234567

平衡二叉查找樹:

                     4

                2        6

          1       3   5     7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章