这些算法的思路很多我不会的话都参考了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);
}
}
打印地方是调试用的~