将二元树转换成一个排序的双向链表(方法一)

这个题目是微软的面试题,将二元树转换成一个排序的双向链表,直接贴代码!


该方法通过递归方式转换二叉树,分别转换根结点的左右子树,然后和根结点连接

/*
 * main.c
 *
 *  Created on: Nov 27, 2013
 *      Author: bing
 *
 *      题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
 *      要求不能创建任何新的结点,只调整指针的指向。
 *
 *		比如将二元查找树
 *                                           10
 *                                         /    \
 *                                       6       14
 *                                     /  \     /  \
 *                                   4     8  12    16
 *			转换成双向链表  4=6=8=10=12=14=16。
 */

#include "bs_tree.h"

#define LEFT 1
#define RIGHT 2

bitree convert(bitree t,int flag);

int main(){
	bitree t,list;
	create_bitree(&t);
	printf("\nSuccess create binary tree!\n");
	printf("Success change binary tree to list!\n");
	printf("created list is:\n");
	list=convert(t,RIGHT);
	for(t=list;t;t=t->rchild)
		printf("%d ",t->data);
	printf("\n");
	return 0;
}

/*
 * 将该二元查找树转换成一个排序的双向链表
 *
 * 	当flag=LEFT时,返回最右段结点的指针;
 * 	当flag=RIGHT时,返回最左段结点的指针;
 *
 * */
bitree convert(bitree t,int flag){

	struct bitnode *left=NULL,*right=NULL,*tmp;
	if(!t)
		return NULL;

	if(!t->lchild && !t->rchild)
		return t;

	if(t->lchild)
		left=convert(t->lchild,LEFT);
	if(t->rchild)
		right=convert(t->rchild,RIGHT);

	if(left)
		left->rchild=t;
	t->lchild=left;

	if(right)
		right->lchild=t;
	t->rchild=right;
	tmp=t;
	if(flag==LEFT){
		while(tmp->rchild)
			tmp=tmp->rchild;
	}
	else{
		while(tmp->lchild)
			tmp=tmp->lchild;
	}
	return tmp;
}


/*
 * bs_tree.h
 *
 *  Created on: Nov 30, 2013
 *      Author: bing
 */

#ifndef BS_TREE_H_
#define BS_TREE_H_
#include <stdio.h>

typedef int TElemType;

typedef struct bitnode{
    TElemType data;
    struct bitnode *lchild,*rchild;
}bitnode,*bitree;

int create_bitree(bitree *t);

#endif /* BS_TREE_H_ */

/*
 * bs_tree.c
 *
 *  Created on: Nov 30, 2013
 *      Author: bing
 *      Binary Search Tree
 */

#include "bs_tree.h"
#include <stdlib.h>

/*
 * 采用中序递归建立二叉树
 * 输入方式可优化为数组赋值
 * */
int create_bitree(bitree *t)
{
	TElemType ch;
	printf("请输入整数:");
    scanf("%d",&ch);

    if(ch==0){
        *t=NULL;
        return 0;
    }
    else
    {
        *t=(bitree)malloc(sizeof(bitnode));
        if(!*t)
            return -1;
        (*t)->data=ch;
        create_bitree(&(*t)->lchild);
        create_bitree(&(*t)->rchild);
    }
    return 0;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值