有序数组放到二叉树 【微软面试100题 第八十六题】

题目要求

  怎样编写一个程序,把一个有序整数数组放到二叉树中?

题目分析

  二叉搜索树:左<中<右。

  因此通过递归,把数组分成两半,左边一半作为左子树然后继续递归,右边一半作为右子树然后继续递归。

代码实现

#include <iostream>
#include <queue>

using namespace std;

typedef struct BinaryTree
{
    struct BinaryTree *left,*right;
    int data;
}BinaryTree;

BinaryTree *ArrayToTree(int *a,int n);
void PrintTree(BinaryTree *root);

int main(void)
{
    int a[] = {2,3,5,6,8,10};
    BinaryTree *tree = ArrayToTree(a,6);
    PrintTree(tree);
    return 0;
}
void PrintTree(BinaryTree *root)
{
    if(root==NULL)
        return ;
    queue<BinaryTree *> queueTemp;
    queueTemp.push(root);
    queueTemp.push(0);
    while(!queueTemp.empty())
    {
        BinaryTree *tmp = queueTemp.front();
        queueTemp.pop();
        if(tmp)
        {
            cout << tmp->data << " ";
            if(tmp->left)
                queueTemp.push(tmp->left);
            if(tmp->right)
                queueTemp.push(tmp->right);
        }
        else if(!queueTemp.empty())
        {
            queueTemp.push(0);
            cout << endl;
        }
    }
}
BinaryTree *ArrayToTreeCore(int *a,int start,int end)
{
    if(start>end)
        return NULL;
    int mid = start + (end-start)/2;
    BinaryTree *root = new BinaryTree;
    root->data = a[mid];
    root->left = ArrayToTreeCore(a,start,mid-1);
    root->right = ArrayToTreeCore(a,mid+1,end);

    return root;
}
BinaryTree *ArrayToTree(int *a,int n)
{
    if(a==NULL || n<=0)
        return NULL;
    return ArrayToTreeCore(a,0,n-1);
}

 

转载于:https://www.cnblogs.com/tractorman/p/4123162.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值