forked from soulmachine/acm-cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchapTree.tex
2562 lines (2149 loc) · 72.9 KB
/
chapTree.tex
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\chapter{树}
\section{二叉树的遍历} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:binaryTreeTraversal}
在中序遍历中,一个节点的前驱,是其左子树的最右下角结点,后继,是其右子树的最左下角结点。
在后序遍历中,
\begindot
\item 若结点是根结点,则其后继为空;
\item 若结点是双亲的右子树,或是左子树但双亲无右子树,则其后继为双亲结点;
\item 若结点是双亲的左子树且双亲有右子树,则其后继为右子树按后序遍历的第一个结点
\myenddot
\begin{Codex}[label=binary_tree.cpp]
#include <iostream>
#include <stack>
#include <queue>
/** 结点的数据 */
typedef int tree_node_elem_t;
/*
*@struct
*@brief 二叉树结点
*/
typedef struct binary_tree_node_t {
binary_tree_node_t *left; /* 左孩子*/
binary_tree_node_t *right; /* 右孩子*/
tree_node_elem_t elem; /* 结点的数据*/
} binary_tree_node_t;
/**
* @brief 先序遍历,递归.
* @param[in] root 根结点
* @param[in] visit 访问数据元素的函数指针
* @return 无
*/
void pre_order_r(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
if (root == NULL) return;
visit(root);
pre_order_r(root->left, visit);
pre_order_r(root->right, visit);
}
/**
* @brief 中序遍历,递归.
*/
void in_order_r(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
if(root == NULL) return;
in_order_r(root->left, visit);
visit(root);
in_order_r(root->right, visit);
}
/**
* @brief 后序遍历,递归.
*/
void post_order_r(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
if(root == NULL) return;
post_order_r(root->left, visit);
post_order_r(root->right, visit);
visit(root);
}
/**
* @brief 先序遍历,非递归.
*/
void pre_order(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
const binary_tree_node_t *p;
stack<const binary_tree_node_t *> s;
p = root;
if(p != NULL) s.push(p);
while(!s.empty()) {
p = s.top();
s.pop();
visit(p);
if(p->right != NULL) s.push(p->right);
if(p->left != NULL) s.push(p->left);
}
}
/**
* @brief 中序遍历,非递归.
*/
void in_order(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
const binary_tree_node_t *p;
stack<const binary_tree_node_t *> s;
p = root;
while(!s.empty() || p!=NULL) {
if(p != NULL) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
visit(p);
p = p->right;
}
}
}
/**
* @brief 后序遍历,非递归.
*/
void post_order(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
/* p,正在访问的结点,q,刚刚访问过的结点*/
const binary_tree_node_t *p, *q;
stack<const binary_tree_node_t *> s;
p = root;
do {
while(p != NULL) { /* 往左下走*/
s.push(p);
p = p->left;
}
q = NULL;
while(!s.empty()) {
p = s.top();
s.pop();
/* 右孩子不存在或已被访问,访问之*/
if(p->right == q) {
visit(p);
q = p; /* 保存刚访问过的结点*/
} else {
/* 当前结点不能访问,需第二次进栈*/
s.push(p);
/* 先处理右子树*/
p = p->right;
break;
}
}
} while(!s.empty());
}
/**
* @brief 层次遍历,也即BFS.
*
* 跟先序遍历一模一样,唯一的不同是栈换成了队列
*/
void level_order(const binary_tree_node_t *root,
int (*visit)(const binary_tree_node_t*)) {
const binary_tree_node_t *p;
queue<const binary_tree_node_t *> q;
p = root;
if(p != NULL) q.push(p);
while(!q.empty()) {
p = q.front();
q.pop();
visit(p);
/*先左后右或先右后左无所谓*/
if(p->left != NULL) q.push(p->left);
if(p->right != NULL) q.push(p->right);
}
}
\end{Codex}
\section{线索二叉树} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
二叉树中存在很多空指针,可以利用这些空指针,指向其前驱或者后继。这种利用起来的空指针称为线索,这种改进后的二叉树称为线索二叉树(threaded binary tree)。
一棵n个结点的二叉树含有n+1个空指针。这是因为,假设叶子节点数为$n_0$,度为1的节点数为$n_1$,度为2的节点数为$n_2$,每个叶子节点有2个空指针,每个度为1的节点有1个空指针,则空指针的总数为$2n_0+n_1$,又有$n_0=n_2+1$(留给读者证明),因此空指针总数为$2n_0+n_1=n_0+n_2+1+n_1=n_0+n_1+n_2+1=n+1$。
在二叉树线索化过程中,通常规定,若无左子树,令lchild指向前驱,若无右子树,令rchild指向后继。还需要增加两个标志域表示当前指针是不是线索,例如ltag=1,表示lchild指向的是前驱,ltag=0,表示lchild指向的是左孩子,rtag类似。
二叉树的线索化,实质上就是遍历一棵树,只是在遍历的过程中,检查当前节点的左右指针是否为空,若为空,将它们改为指向前驱或后继的线索。
以中序线索二叉树为例,指针pre表示前驱,succ表示后继,如图~\ref{fig:threadedBinaryTree}所示。
\begin{center}
\includegraphics[width=300pt]{threaded-binary-tree.png} \\
\figcaption{中序线索二叉树}\label{fig:threadedBinaryTree}
\end{center}
在中序线索二叉树中,一个节点的前驱,是其左子树的最右下角结点,后继,是其右子树的最左下角结点。
中序线索二叉树的C语言实现如下。
\begin{Codex}[label=theaded_binary_tree.c]
/** @file threaded_binary_tree.c
* @brief 线索二叉树.
*/
#include <stddef.h> /* for NULL */
#include <stdio.h>
/* 结点数据的类型. */
typedef int elem_t;
/**
*@struct
*@brief 线索二叉树结点.
*/
typedef struct tbt_node_t {
int ltag; /** 1表示是线索,0表示是孩子 */
int rtag; /** 1表示是线索,0表示是孩子 */
struct tbt_node_t *left; /** 左孩子*/
struct tbt_node_t *right; /** 右孩子*/
elem_t elem; /** 结点所存放的数据*/
}tbt_node_t;
/* 内部函数 */
static void in_thread(tbt_node_t *p, tbt_node_t **pre);
static tbt_node_t *first(tbt_node_t *p);
static tbt_node_t *next(const tbt_node_t *p);
/**
* @brief 建立中序线索二叉树.
* @param[in] root 树根
* @return 无
*/
void create_in_thread(tbt_node_t *root) {
/* 前驱结点指针*/
tbt_node_t *pre=NULL;
if(root != NULL) { /* 非空二叉树,线索化*/
/* 中序遍历线索化二叉树*/
in_thread(root, &pre);
/* 处理中序最后一个结点*/
pre->right = NULL;
pre->rtag = 1;
}
}
/**
* @brief 在中序线索二叉树上执行中序遍历.
* @param[in] root 树根
* @param[in] visit 访问结点的数据的函数
* @return 无
*/
void in_order(tbt_node_t *root, int(*visit)(tbt_node_t*)) {
tbt_node_t *p;
for(p = first(root); p != NULL; p = next(p)) {
visit(p);
}
}
/*
* @brief 中序线索化二叉树的主过程.
* @param[in] p 当前要处理的结点
* @param[inout] pre 当前结点的前驱结点
* @return 无
*/
static void in_thread(tbt_node_t *p, tbt_node_t **pre) {
if(p != NULL) {
in_thread(p->left, pre); /* 线索化左子树 */
if(p->left == NULL) { /* 左子树为空,建立前驱 */
p->left = *pre;
p->ltag = 1;
}
/* 建立前驱结点的后继线索 */
if((*pre) != NULL &&
(*pre)->right == NULL) {
(*pre)->right = p;
(*pre)->rtag = 1;
}
*pre = p; /* 更新前驱 */
in_thread(p->right, pre); /* 线索化右子树 */
}
}
/*
* @brief 寻找线索二叉树的中序下的第一个结点.
* @param[in] p 线索二叉树中的任意一个结点
* @return 此线索二叉树的第一个结点
*/
static tbt_node_t *first(tbt_node_t *p) {
if(p == NULL) return NULL;
while(p->ltag == 0) {
p = p->left; /* 最左下结点,不一定是叶结点*/
}
return p;
}
/*
* @brief 求中序线索二叉树中某结点的后继.
* @param[in] p 某结点
* @return p的后继
*/
static tbt_node_t *next(const tbt_node_t *p) {
if(p->rtag == 0) {
return first(p->right);
} else {
return p->right;
}
}
\end{Codex}
中序线索二叉树最简单,在中序线索的基础上稍加修改就可以实现先序,后续就要再费点心思了。
\section{Morris Traversal} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
通过前面第\S \ref{sec:binaryTreeTraversal}节,我们知道,实现二叉树的前序(preorder)、中序(inorder)、后序(postorder)遍历有两个常用的方法,一是递归(recursive),二是栈(stack+iterative)。这两种方法都是O(n)的空间复杂度。
而Morris Traversal只需要O(1)的空间复杂度。这种算法跟线索二叉树很像,不过Morris Traversal一边建线索,一边访问数据,访问完后销毁线索,保持二叉树不变。
\subsection{Morris中序遍历}
Morris中序遍历的步骤如下:
\begin{enumerate}
\item 初始化当前节点cur为root节点
\item 如果cur没有左孩子,则输出当前节点并将其右孩子作为当前节点,即cur = cur->right。
\item 如果cur有左孩子,则寻找cur的前驱,即cur的左子树的最右下角结点。\\
a) 如果前驱节点的右孩子为空,将它的右孩子指向当前节点,当前节点更新为当前节点的左孩子。\\
b) 如果前驱节点的右孩子为当前节点,将它的右孩子重新设为空(恢复树的形状),输出当前节点,当前节点更新为当前节点的右孩子。
\item 重复2、3步骤,直到cur为空。
\end{enumerate}
如图~\ref{fig:inorderMorris}所示,cur表示当前节点,深色节点表示该节点已输出。
\begin{center}
\includegraphics[width=360pt]{inorder-morris-traversal.png} \\
\figcaption{Morris中序遍历}\label{fig:inorderMorris}
\end{center}
C语言实现见第\S\ref{sec:morrisTraversalImpl}节。
\subsubsection{相关的题目}
\begindot
\item Leet Code - Binary Tree Inorder Traversal, \myurl{http://leetcode.com/onlinejudge\#question_94}
\myenddot
\subsection{Morris先序遍历}
Morris先序遍历的步骤如下:
\begin{enumerate}
\item 初始化当前节点cur为root节点
\item 如果cur没有左孩子,则输出当前节点并将其右孩子作为当前节点,即cur = cur->right。
\item 如果cur有左孩子,则寻找cur的前驱,即cur的左子树的最右下角结点。\\
a) 如果前驱节点的右孩子为空,将它的右孩子指向当前节点,\textbf{输出当前节点(在这里输出,这是与中序遍历唯一的不同点)}当前节点更新为当前节点的左孩子。\\
b) 如果前驱节点的右孩子为当前节点,将它的右孩子重新设为空(恢复树的形状),\sout{输出当前节点,}当前节点更新为当前节点的右孩子。
\item 重复2、3步骤,直到cur为空。
\end{enumerate}
如图~\ref{fig:preorderMorris}所示。
\begin{center}
\includegraphics[width=360pt]{preorder-morris-traversal.png} \\
\figcaption{Morris先序遍历}\label{fig:preorderMorris}
\end{center}
C语言实现见第\S\ref{sec:morrisTraversalImpl}节。
\subsection{Morris后序遍历}
Morris后续遍历稍微复杂,需要建立一个临时节点dump,令其左孩子是root,并且还需要一个子过程,就是倒序输出某两个节点之间路径上的所有节点。
Morris后序遍历的步骤如下:
\begin{enumerate}
\item 初始化当前节点cur为root节点
\item 如果cur没有左孩子,则\sout{输出当前节点并}将其右孩子作为当前节点,即cur = cur->right。
\item 如果cur有左孩子,则寻找cur的前驱,即cur的左子树的最右下角结点。\\
a) 如果前驱节点的右孩子为空,将它的右孩子指向当前节点,当前节点更新为当前节点的左孩子。\\
b) 如果前驱节点的右孩子为当前节点,将它的右孩子重新设为空(恢复树的形状),\sout{输出当前节点,}\textbf{倒序输出从当前节点的左孩子到该前驱节点这条路径上的所有节点。}当前节点更新为当前节点的右孩子。
\item 重复2、3步骤,直到cur为空。
\end{enumerate}
如图~\ref{fig:postorderMorris}所示。
\begin{center}
\includegraphics[width=360pt]{postorder-morris-traversal.png} \\
\figcaption{Morris后序遍历}\label{fig:postorderMorris}
\end{center}
C语言实现见第\S\ref{sec:morrisTraversalImpl}节。
\subsection{C语言实现}
\label{sec:morrisTraversalImpl}
\begin{Codex}[label=morris_traversal.c]
/** @file morris_traversal.c
* @brief Morris遍历算法.
*/
#include<stdio.h>
#include<stdlib.h>
/* 结点数据的类型. */
typedef int elem_t;
/**
*@struct
*@brief 二叉树结点.
*/
typedef struct bt_node_t {
elem_t elem; /* 节点的数据 */
struct bt_node_t *left; /* 左孩子 */
struct bt_node_t *right; /* 右孩子 */
} bt_node_t;
/**
* @brief 中序遍历,Morris算法.
* @param[in] root 根节点
* @param[in] visit 访问函数
* @return 无
*/
void in_order_morris(bt_node_t *root, int(*visit)(bt_node_t*)) {
bt_node_t *cur, *prev;
cur = root;
while (cur != NULL ) {
if (cur->left == NULL ) {
visit(cur);
prev = cur;
cur = cur->right;
} else {
/* 查找前驱 */
bt_node_t *node = cur->left;
while (node->right != NULL && node->right != cur)
node = node->right;
if (node->right == NULL ) { /* 还没线索化,则建立线索 */
node->right = cur;
/* prev = cur; 不能有这句,cur还没有被访问 */
cur = cur->left;
} else { /* 已经线索化,则访问节点,并删除线索 */
visit(cur);
node->right = NULL;
prev = cur;
cur = cur->right;
}
}
}
}
/**
* @brief 先序遍历,Morris算法.
* @param[in] root 根节点
* @param[in] visit 访问函数
* @return 无
*/
void pre_order_morris(bt_node_t *root, int (*visit)(bt_node_t*)) {
bt_node_t *cur, *prev;
cur = root;
while (cur != NULL ) {
if (cur->left == NULL ) {
visit(cur);
prev = cur; /* cur刚刚被访问过 */
cur = cur->right;
} else {
/* 查找前驱 */
bt_node_t *node = cur->left;
while (node->right != NULL && node->right != cur)
node = node->right;
if (node->right == NULL ) { /* 还没线索化,则建立线索 */
visit(cur); /* 仅这一行的位置与中序不同 */
node->right = cur;
prev = cur; /* cur刚刚被访问过 */
cur = cur->left;
} else { /* 已经线索化,则删除线索 */
node->right = NULL;
/* prev = cur; 不能有这句,cur已经被访问 */
cur = cur->right;
}
}
}
}
static void reverse(bt_node_t *from, bt_node_t *to);
static void visit_reverse(bt_node_t* from, bt_node_t *to,
int (*visit)(bt_node_t*));
/**
* @brief 后序遍历,Morris算法.
* @param[in] root 根节点
* @param[in] visit 访问函数
* @return 无
*/
void post_order_morris(bt_node_t *root, int (*visit)(bt_node_t*)) {
bt_node_t dummy = { 0, NULL, NULL };
bt_node_t *cur, *prev = NULL;
dummy.left = root;
cur = &dummy;
while (cur != NULL ) {
if (cur->left == NULL ) {
prev = cur; /* 必须要有 */
cur = cur->right;
} else {
bt_node_t *node = cur->left;
while (node->right != NULL && node->right != cur)
node = node->right;
if (node->right == NULL ) { /* 还没线索化,则建立线索 */
node->right = cur;
prev = cur; /* 必须要有 */
cur = cur->left;
} else { /* 已经线索化,则访问节点,并删除线索 */
visit_reverse(cur->left, prev, visit); // call print
prev->right = NULL;
prev = cur; /* 必须要有 */
cur = cur->right;
}
}
}
}
/*
* @brief 逆转路径.
* @param[in] from from
* @param[to] to to
* @return 无
*/
static void reverse(bt_node_t *from, bt_node_t *to) {
bt_node_t *x = from, *y = from->right, *z;
if (from == to) return;
while (x != to) {
z = y->right;
y->right = x;
x = y;
y = z;
}
}
/*
* @brief 访问逆转后的路径上的所有结点.
* @param[in] from from
* @param[to] to to
* @return 无
*/
static void visit_reverse(bt_node_t* from, bt_node_t *to,
int (*visit)(bt_node_t*)) {
bt_node_t *p = to;
reverse(from, to);
while (1) {
visit(p);
if (p == from)
break;
p = p->right;
}
reverse(to, from);
}
/*
* @brief 分配一个新节点.
* @param[in] e 新节点的数据
* @return 新节点
*/
bt_node_t* new_node(int e) {
bt_node_t* node = (bt_node_t*) malloc(sizeof(bt_node_t));
node->elem = e;
node->left = NULL;
node->right = NULL;
return (node);
}
static int print(bt_node_t *node) {
printf(" %d ", node->elem);
return 0;
}
/* test */
int main() {
/* 构造的二叉树如下
1
/ \
2 3
/ \
4 5
*/
bt_node_t *root = new_node(1);
root->left = new_node(2);
root->right = new_node(3);
root->left->left = new_node(4);
root->left->right = new_node(5);
in_order_morris(root, print);
printf("\n");
pre_order_morris(root, print);
printf("\n");
post_order_morris(root, print);
printf("\n");
return 0;
}
\end{Codex}
\section{重建二叉树} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{Codex}[label=binary_tree_rebuild.c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
/**
* @brief 给定前序遍历和中序遍历,输出后序遍历.
*
* @param[in] pre 前序遍历的序列
* @param[in] in 中序遍历的序列
* @param[in] n 序列的长度
* @param[out] post 后续遍历的序列
* @return 无
*/
void build_post(const char * pre, const char *in, const int n, char *post) {
int left_len = strchr(in, pre[0]) - in;
if(n <= 0) return;
build_post(pre + 1, in, left_len, post);
build_post(pre + left_len + 1, in + left_len + 1,
n - left_len - 1, post + left_len);
post[n - 1] = pre[0];
}
#define MAX 64
// 测试
// BCAD CBAD,输出 CDAB
// DBACEGF ABCDEFG,输出 ACBFGED
void build_post_test() {
char pre[MAX] = {0};
char in[MAX] = {0};
char post[MAX] = {0};
int n;
scanf("%s%s", pre, in);
n = strlen(pre);
build_post(pre, in, n, post);
printf("%s\n", post);
}
/* 结点数据的类型. */
typedef char elem_t;
/**
*@struct
*@brief 二叉树结点.
*/
typedef struct bt_node_t {
elem_t elem; /* 节点的数据 */
struct bt_node_t *left; /* 左孩子 */
struct bt_node_t *right; /* 右孩子 */
} bt_node_t;
/**
* @brief 给定前序遍历和中序遍历,重建二叉树.
*
* @param[in] pre 前序遍历的序列
* @param[in] in 中序遍历的序列
* @param[in] n 序列的长度
* @param[out] root 根节点
* @return 无
*/
void rebuild(const char *pre, const char *in, int n, bt_node_t **root) {
int left_len;
// 检查终止条件
if (n <= 0 || pre == NULL || in == NULL)
return;
//获得前序遍历的第一个结点
*root = (bt_node_t*) malloc(sizeof(bt_node_t));
(*root)->elem = *pre;
(*root)->left = NULL;
(*root)->right = NULL;
left_len = strchr(in, pre[0]) - in;
//重建左子树
rebuild(pre + 1, in, left_len, &((*root)->left));
//重建右子树
rebuild(pre + left_len + 1, in + left_len + 1, n - left_len - 1,
&((*root)->right));
}
void print_post_order(const bt_node_t *root) {
if(root != NULL) {
print_post_order(root->left);
print_post_order(root->right);
printf("%c", root->elem);
}
}
void rebuild_test() {
char pre[MAX] = { 0 };
char in[MAX] = { 0 };
int n;
bt_node_t *root;
scanf("%s%s", pre, in);
n = strlen(pre);
rebuild(pre, in, n, &root);
print_post_order(root);
}
int main() {
build_post_test();
rebuild_test();
return 0;
}
\end{Codex}
\section{堆} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{原理和实现}
C++可以直接使用\fn{priority_queue}。
\begin{Codex}[label=heap.c]
/** @file heap.c
* @brief 堆,默认为小根堆,即堆顶为最小.
* @author [email protected]
*/
#include <stdlib.h> /* for malloc() */
#include <string.h> /* for memcpy() */
typedef int heap_elem_t; // 元素的类型
/**
* @struct
* @brief 堆的结构体
*/
typedef struct heap_t {
int size; /** 实际元素个数 */
int capacity; /** 容量,以元素为单位 */
heap_elem_t *elems; /** 堆的数组 */
int (*cmp)(const heap_elem_t*, const heap_elem_t*); /** 元素的比较函数 */
}heap_t;
/** 基本类型(如int, long, float, double)的比较函数 */
int cmp_int(const int *x, const int *y) {
const int sub = *x - *y;
if(sub > 0) {
return 1;
} else if(sub < 0) {
return -1;
} else {
return 0;
}
}
/**
* @brief 创建堆.
* @param[out] capacity 初始容量
* @param[in] cmp cmp 比较函数,小于返回-1,等于返回0
* 大于返回1,反过来则是大根堆
* @return 成功返回堆对象的指针,失败返回 NULL
*/
heap_t* heap_create(const int capacity,
int (*cmp)(const heap_elem_t*, const heap_elem_t*)) {
heap_t *h = (heap_t*)malloc(sizeof(heap_t));
h->size = 0;
h->capacity = capacity;
h->elems = (heap_elem_t*)malloc(capacity * sizeof(heap_elem_t));
h->cmp = cmp;
return h;
}
/**
* @brief 销毁堆.
* @param[inout] h 堆对象的指针
* @return 无
*/
void heap_destroy(heap_t *h) {
free(h->elems);
free(h);
}
/**
* @brief 判断堆是否为空.
* @param[in] h 堆对象的指针
* @return 是空,返回 1,否则返回 0
*/
int heap_empty(const heap_t *h) {
return h->size == 0;
}
/**
* @brief 获取元素个数.
* @param[in] s 堆对象的指针
* @return 元素个数
*/
int heap_size(const heap_t *h) {
return h->size;
}
/*
* @brief 小根堆的自上向下筛选算法.
* @param[in] h 堆对象的指针
* @param[in] start 开始结点
* @return 无
*/
void heap_sift_down(const heap_t *h, const int start) {
int i = start;
int j;
const heap_elem_t tmp = h->elems[start];
for(j = 2 * i + 1; j < h->size; j = 2 * j + 1) {
if(j < (h->size - 1) &&
// h->elems[j] > h->elems[j + 1]
h->cmp(&(h->elems[j]), &(h->elems[j + 1])) > 0) {
j++; /* j 指向两子女中小者*/
}
// tmp <= h->data[j]
if(h->cmp(&tmp, &(h->elems[j])) <= 0) {
break;
} else {
h->elems[i] = h->elems[j];
i = j;
}
}
h->elems[i] = tmp;
}
/*
* @brief 小根堆的自下向上筛选算法.
* @param[in] h 堆对象的指针
* @param[in] start 开始结点
* @return 无
*/
void heap_sift_up(const heap_t *h, const int start) {
int j = start;
int i= (j - 1) / 2;
const heap_elem_t tmp = h->elems[start];
while(j > 0) {
// h->data[i] <= tmp
if(h->cmp(&(h->elems[i]), &tmp) <= 0) {
break;
} else {
h->elems[j] = h->elems[i];
j = i;
i = (i - 1) / 2;
}
}
h->elems[j] = tmp;
}
/**
* @brief 添加一个元素.
* @param[in] h 堆对象的指针
* @param[in] x 要添加的元素
* @return 无
*/
void heap_push(heap_t *h, const heap_elem_t x) {
if(h->size == h->capacity) { /*已满,重新分配内存*/
heap_elem_t* tmp =
(heap_elem_t*)realloc(h->elems, h->capacity * 2 * sizeof(heap_elem_t));
h->elems = tmp;
h->capacity *= 2;
}
h->elems[h->size] = x;
h->size++;
heap_sift_up(h, h->size - 1);
}
/**
* @brief 弹出堆顶元素.
* @param[in] h 堆对象的指针
* @return 无
*/
void heap_pop(heap_t *h) {
h->elems[0] = h->elems[h->size - 1];
h->size --;
heap_sift_down(h, 0);
}
/**
* @brief 获取堆顶元素.
* @param[in] h 堆对象的指针
* @return 堆顶元素
*/
heap_elem_t heap_top(const heap_t *h) {
return h->elems[0];
}
\end{Codex}
\subsection{最小的N个和} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsubsection{描述}
有两个长度为$N$的序列 A 和 B,在 A 和 B 中各任取一个数可以得到 $N^2$ 个和,求这$N^2$ 个和中最小的$N$个。
\subsubsection{输入}
第一行输入一个正整数$N$;第二行N个整数$A_i$ 且$A_i \leq 10^9$;第三行$N$个整数$B_i$,且$Bi \leq 10^9$。
\subsubsection{输出}
输出仅一行,包含$N$个整数,从小到大输出这$N$个最小的和,相邻数字之间用空格隔开。
\subsubsection{样例输入}
\begin{Code}
5
1 3 2 4 5
6 3 4 1 7
\end{Code}
\subsubsection{样例输出}
\begin{Code}
2 3 4 4 5
\end{Code}
\subsubsection{分析}
由于数据太大,有$N^2$个和,不能通过先求和再排序的方式来求解,这个时候就要用到堆了。
首先将A,B两数组排序,我们可以建立这样一个有序表:
\begin{eqnarray}
A_1+B_1<A_1+B_2<A_1+B_3< &...& <A_1+B_N \nonumber \\
A_2+B_1<A_2+B_2<A_2+B_3< &...& <A_2+B_N \nonumber \\
& ... \nonumber \\
A_N+B_1<A_N+B_2<A_N+B_3< &...& <A_N+B_N \nonumber
\end{eqnarray}
首先将\fn{A[i] + B[0]}压入堆中,设每次出堆的元素为\fn{sum=A[a]+B[b]},则将\fn{A[a]+B[b+1]}入堆,这样可以保证前$N$个出堆的元素为最小的前$N$项。在实现的时候,可以不用保存B数组的下标,通过\fn{sum-B[b]+B[b+1]}来替换\fn{A[a]+B[b+1]}来节省空间。
\subsubsection{代码}
\begin{Codex}[label=sequence.c]
/* wikioi 1245 最小的N个和,http://www.wikioi.com/problem/1245/ */
#include <stdio.h>
#include <stdlib.h> /* for malloc() */
#include <string.h> /* for memcpy() */
#define MAXN 100000
int N;
int a[MAXN], b[MAXN];
typedef struct node_t {
int sum;
int b; /* sum=a[i]+b[b] */
} node_t;
typedef node_t heap_elem_t; // 元素的类型
/* 等价于复制粘贴,这里为了节约篇幅,使用include,在OJ上提交时请用复制粘贴 */
#include "heap.c"
void k_merge() {
heap_t *h;
int i;
node_t tmp;
qsort(a, N, sizeof(int), cmp_int);
qsort(b, N, sizeof(int), cmp_int);
h = heap_create(N, cmp_node);
for (i = 0; i < N; i++) {
tmp.sum = a[i]+b[0];
tmp.b = 0;
heap_push(h, tmp);
}
for (i = 0; i < N; i++) {
tmp = heap_top(h); heap_pop(h);
printf("%d ", tmp.sum);
tmp.sum = tmp.sum - b[tmp.b] + b[tmp.b + 1];
tmp.b++;
heap_push(h, tmp);
}
heap_destroy(h);
return;
}
int main() {
int i;
scanf("%d", &N);
for (i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < N; i++) {
scanf("%d", &b[i]);
}
k_merge();
return 0;
}
\end{Codex}
\subsubsection{相关的题目}
与本题相同的题目:
\begindot
\item wikioi 1245 最小的N个和, \myurl{http://www.wikioi.com/problem/1245/}
\myenddot
与本题相似的题目:
\begindot
\item POJ 2442 Sequence, \myurl{http://poj.org/problem?id=2442}
\myenddot