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

来源:互联网 发布:java如何定义一个函数 编辑:程序博客网 时间:2024/05/17 02:46

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


该方法在中序遍历二叉树时,完成指针的转换;

/* * main.c * *  Created on: Nov 30, 2013 *      Author: bing * *      题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。 *      要求不能创建任何新的结点,只调整指针的指向。 * *比如将二元查找树 *                                           10 *                                         /    \ *                                       6       14 *                                     /  \     /  \ *                                   4     8  12    16 *转换成双向链表  4=6=8=10=12=14=16。 */#include "bs_tree.h"bitree convert_inorder(bitree t);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_inorder(t);for(t=list;t;t=t->rchild)printf("%d ",t->data);printf("\n");return 0;}/* * 中序遍历将该二元查找树转换成一个排序的双向链表 * */bitree pre;int visit(bitree b){if(!b)return 1;if(!pre)pre=b;else{b->lchild=pre;pre->rchild=b;pre=b;}    return 0;}bitree convert_inorder(bitree t){bitree tmp=t;inorder_traverse_recursion(t,visit);while(tmp->lchild)tmp=tmp->lchild;return tmp;}


/* * 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;}int inorder_traverse_recursion(bitree t,int (*visit)(bitree e)){    if(t)    {inorder_traverse_recursion(t->lchild,visit);visit(t);inorder_traverse_recursion(t->rchild,visit);return 0;    }    return 1;}

/* * 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);int inorder_traverse_recursion(bitree t,int (*visit)(bitree e));#endif /* BS_TREE_H_ */


尴尬,没注意到题目中不让使用任何指针,我使用了全局指针...好吧,我错了,不过我感觉这个方法更简单,在中序遍历中的visit()函数中实现指针的转换