微软面试题1 二元查找树转变为双向链表

二元查找树最大的特点就是左孩子节点小于父亲节点,右孩子节点大于父亲节点,所以在中序遍历的时候,进行一下指针的改变即可。

具体的步骤就是先根据输入建立树,然后在中序遍历的时候,确定head和tail,head的确定可以是最左子树,也就是中序遍历第一个输出的元素。

然后tail的确定可以采取迭代赋值的方式,最后一个输出的元素就是tail;

原题如下 1.把二元查找树转变成排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。


我的代码,如果有不对,请指正


#include <stdio.h>
#include <malloc.h>
typedef struct  searchTree
{
       int data;
       struct searchTree *lchild;
       struct searchTree  *rchild;
}*Tree;
Tree temp=NULL;
Tree head=NULL;
Tree  tail;
int midtravelToList(Tree tree)
{
    //printf("tree=%d ",tree);
    if(tree!=NULL)
    {
        midtravelToList((tree)->lchild);
        printf("%d ",(tree)->data);
        if(temp==NULL)
        {
                                        temp=tree;
                                        head=tree;
        }
        else
        {
            temp->rchild=tree;
            (tree)->lchild=temp;
            temp=tree;
            tail=tree;
        }
        midtravelToList((tree)->rchild);
    }
}
Tree  createTree(int array[],int length)
{
    Tree nodes[100];
    int i=0;
    int j;
    for(i=0;i<length;i++)
    {
        if(array[i]!=-1)
        {
            nodes[i]=(Tree *)malloc(sizeof(struct searchTree));
            nodes[i]->data=array[i];
            nodes[i]->lchild=NULL;
            nodes[i]->rchild=NULL;
            j=(i-1)/2;
            if(i%2==1&&i>0)
            {
                nodes[j]->lchild=nodes[i];
            }
            else if(i>0)
            {
                nodes[j]->rchild=nodes[i];
            }
                                     
        }
        else
        {
            nodes[i]=NULL;
        }
    }
    return nodes[0];
}
int travelList(Tree tree)
{
    Tree t=tree;
    while(t!=NULL)
    {
        printf("%d ",t->data);
        t=t->rchild;
    }
}
int reverseTravelList(Tree tree)
{
    Tree t=tree;
    while(t!=NULL)
    {
        printf("%d ",t->data);
        t=t->lchild;
    }
}
int main()
{
    Tree  searchTree;
    int array[100];
    int i=0;
    printf("input ,-1 represents null.,ends with '#'\n");
                while(scanf("%d",&array[i])==1)
                {
                    i++;
                }
                searchTree=createTree(array,i);
                midtravelToList(searchTree);
                printf("\n");
                travelList(head);
                printf("\n");
                reverseTravelList(tail);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值