二叉查找树转换为排序的双向链表

#include <stdio.h>
#include <stdlib.h>

typedef struct BSTreeNode{
	int value;
	struct BSTreeNode *left;
	struct BSTreeNode *right;
} BSTreeNode;



void mid_traverse(BSTreeNode *n){
	if(n == NULL)
		return;
	mid_traverse(n->left);
	printf("%4d", n->value);
	mid_traverse(n->right);
}

BSTreeNode *insert_node(BSTreeNode *p, int v){
	if(p == NULL){
		p = (BSTreeNode *)malloc(sizeof(BSTreeNode));		
		p->value = v;
		p->left = NULL;
	 	p->right = NULL;
	}else{
		if(p->value > v){
			p->left = insert_node(p->left, v);
		}
		if(p->value < v){
			p->right = insert_node(p->right, v);
		}	
	}
	return p;
}

BSTreeNode *convert(BSTreeNode *p){
	if(p == NULL) return NULL;
	BSTreeNode *leftMax, *rightMin;
	leftMax = p->left;
	rightMin = p->right;
	if(leftMax != NULL && leftMax->right != NULL)
		leftMax = leftMax->right;
	if(rightMin != NULL && rightMin->left != NULL)
		rightMin = rightMin->left;
	convert(p->left);
	convert(p->right);
	if(leftMax != NULL)
		leftMax->right =  p;
	p->left = leftMax;
	if(rightMin != NULL)
		rightMin->left = p;
	p->right = rightMin;
	return p;
	
}

BSTreeNode *getLeast (BSTreeNode *p){
	while(p != NULL && p->left != NULL)
		p = p->left;	
	return p;
}

int main (void) {
	BSTreeNode *pRoot = NULL;
	BSTreeNode *pLeast = NULL;
	BSTreeNode *p;
	pRoot = insert_node(pRoot, 10);
	insert_node(pRoot, 6);
	insert_node(pRoot, 14);
	insert_node(pRoot, 4);
	insert_node(pRoot, 8);
	insert_node(pRoot, 12);
	insert_node(pRoot, 16);
	mid_traverse(pRoot);
	printf("\n");
	pLeast = getLeast(pRoot);
	printf("%d\n", pLeast->value);
	convert(pRoot);
	for(p=pLeast;p!=NULL;p=p->right)
		printf("%4d",p->value);
	return 1;
}
 

你可能感兴趣的:(二叉查找树)