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

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


該方法在中序遍歷二叉樹時,完成指針的轉換;

/*
 * 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()函數中實現指針的轉換
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章