SanfenR的博客

二叉树转换成双向链表(day6)

题目

  • 题目:输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
    要求不能创建任何新的结点,只调整指针的指向。比如将二元查找树
1
2
3
4
5
6
7
8
10
/ \
6 14
/ \ / \
4 8 12 16
转换成双向链表4=6=8=10=12=14=16

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
struct Node {
int value;
Node* left;
Node* right;
};
bool createList(Node* head, Node* &left, Node* &right){
left = head;
right = head;
if(!head){
return false;
} else {
Node *l1, *r1, *l2, *r2;
l1 = NULL;
r1 = NULL;
l2 = NULL;
r2 = NULL;
if(createList(head->left, l1, r1)){
head->left = r1;
r1->right = head;
left = l1;
}
if(createList(head->right, l2, r2)){
head->right=l2;
l2->left=head;
right = r2;
}
return true;
}
}
int main(){
Node n4={4,NULL,NULL};
Node n5={8,NULL,NULL};
Node n6={12,NULL,NULL};
Node n7={16, NULL, NULL};
Node n2={6,&n4,&n5};
Node n3={14,&n6,&n7};
Node n1={10,&n2,&n3};
Node*Left=NULL;
Node*Right=NULL;
createList(&n1,Left,Right);
while(Left){
cout<<Left->value<<endl;
Left=Left->right;
}
return 0;
}

源码github