将二叉排序树转化成双向链表,不创建新的节点。
下面是非递归的算法。
BiNode* BSTtoList(BiNode *T)
{
BiNode *p, *q;
BiNode *stack[50];
int top = 0;
if (! T) return NULL;
p = T;
q = NULL;
while (top > 0 || p) {
while (p) { //一直走到最左
stack[top++] = p;
p = p->lchild;
}
if (top > 0) {
p = stack[--top];
if (q != NULL) {
q->rchild = p; //rchild域指向节点的直接后继
p->lchild = q; //lchild域指向节点的直接前驱
} else {
T = q = p; // the first node
}
q = p;
p = p->rchild;
}// if (top)
} //while
q->rchild = T; //最后一个节点的rchild指向T
return T;
}
测试代码如下:
#include <stdio.h>
#include <stdlib.h>
#include "../headfiles/BiNode.h"
#include "../sharedSource/BinarySortTree.c"
BiNode* BSTtoList(BiNode *T);
void tranverseBSTtoList(BiNode *T);
int main(void)
{
BiNode *T = NULL;
int ret, key;
printf("input the value of nodes(Ctrl-D to terminate): \n");
while (scanf("%d", &key) != EOF) {
ret = insertBST(&T, key);
if (ret == 0)
printf("insert failed1!\n");
}
printf("tranverse the double linked list:\n");
T = BSTtoList(T);
tranverseBSTtoList(T);
return 0;
}
输出: