將二元樹轉換成一個排序的雙向鏈表(方法一)

這個題目是微軟的面試題,將二元樹轉換成一個排序的雙向鏈表,直接貼代碼!


該方法通過遞歸方式轉換二叉樹,分別轉換根結點的左右子樹,然後和根結點連接

/*
 * 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;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章