这个题目是微软的面试题,将二元树转换成一个排序的双向链表,直接贴代码!
该方法通过递归方式转换二叉树,分别转换根结点的左右子树,然后和根结点连接
/*
* 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;
}