把二元查找树转变成排序的双向链表

这些算法的思路很多我不会的话都参考了July算法的思想,特此声明一下,我只是给出我的具体实现代码!


把二元查找树转变成排序的双向链表

题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node

};


用的递归思想,对于每个节点,相当于连接他左子树的最大节点和右子树的最小节点


#include <stdio.h>
#include <malloc.h>

struct BSTreeNode * createTree();
struct BSTreeNode * treetoList(struct BSTreeNode * root);
void recursion(struct BSTreeNode *& head, struct BSTreeNode *& tail, struct BSTreeNode * root);
void print(struct BSTreeNode * root);
void printtree(struct BSTreeNode * root);

struct BSTreeNode
{
	int treeValue;
	struct BSTreeNode * lchild;
	struct BSTreeNode * rchild;
};

int main()
{
	struct BSTreeNode * root;
	struct BSTreeNode * head;
	root = createTree();
//	printtree(root);
	if(root == NULL) {
		printf("Create tree fail!\n");
		return -1;
	}
	head = treetoList(root);
	print(head);
	return 0;
}

struct BSTreeNode * createTree()
{
	struct BSTreeNode * root;
	int value;
	scanf("%d", &value);
	if(value == 0)
		root = NULL;
	else {
		root = (struct BSTreeNode *)malloc(sizeof(struct BSTreeNode));
		root->treeValue = value;
		printf("Print %d left child\n", value);
		root->lchild = createTree();
		printf("Print %d right child\n", value);
		root->rchild = createTree();
	}
	return root;
}

struct BSTreeNode * treetoList(struct BSTreeNode * root)
{
	struct BSTreeNode * head, * tail;
	recursion(head, tail, root);
	tail->rchild = NULL;
	return head;
}

void recursion(struct BSTreeNode *& head, struct BSTreeNode *& tail, struct BSTreeNode * root)
{
	struct BSTreeNode * ll, * rr;
	if(root == NULL) {
		head = NULL;
		tail = NULL;
		return;
	}
	recursion(head, ll, root->lchild);
	recursion(rr, tail, root->rchild);
	if(ll != NULL) {
		ll->rchild = root;
		root->lchild = ll;
	} else {
		head = root;
	}
	if(rr != NULL) {
		root->rchild = rr;
		rr->lchild = root;
	} else {
		tail = root;
	}
}

void print(struct BSTreeNode * head)
{
	struct BSTreeNode * first;
	for(first = head; first->rchild != NULL; first = first->rchild )
		printf("%d ",first->treeValue);
	printf("%d\n", first->treeValue);
}

void printtree(struct BSTreeNode * root)
{
	if(root) {
		printf("%d ", root->treeValue);
		printtree(root->lchild);
		printtree(root->rchild);
	}
}

打印地方是调试用的~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值