-
Notifications
You must be signed in to change notification settings - Fork 8
/
tree.py
2489 lines (2378 loc) · 95.9 KB
/
tree.py
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
from manimlib.imports import *
from manim_tuan import *
import math
"""
TODO
0: 代码加颜色 | 不同 base_stack 改颜色
1: 选择性补充 levelOrderCreate 函数的代码(因为书本没有加入 层次创建二叉树 的函数)
2: 理清逻辑, 由于使用变量的数量太多了, 且很多顺序都不能轻易更改(如 stack_i 、count 与 mod 等变量), 画一棵清晰的逻辑树用于解释
"""
"""
BUG
1: 全部函数仅适合满二叉树的情况
"""
# preOrder
# inOrder
# postOrder
# levelOrderTraverse
# preOrderCreate
# levelOrderCreate
# 自定义结点信息(结点个数必须 大于 1 小于 15 )
# 因为层次(遍历 | 创建)所用的是非递归代码, 其他(遍历 | 创建)所用的是递归代码, 二者各框架占用空间与内容不一致, 因此分区为两个类
# tree 类 1: 前序顺序建立二叉树 2: 前序遍历二叉树 3: 中序遍历二叉树 4: 后序遍历二叉树
# tree_level 类 1: 层次建立二叉树 2: 层次遍历二叉树
chose = 2
flag = "*" # 空结点的表示方法
# nodeList = "ABD**E**CF**G**" # 前序顺序建立二叉树满结点
# biTree = BiTree(['A', 'B', 'D', '*', '*', 'E', '*', '*', 'C', 'F', '*', '*', 'G', '*', '*'])
nodeList = "ABCDEFG*" # 层次建立二叉树满结点
# biTree = BiTree(['A', 'B', 'C', 'D', 'E', 'F', 'G', '*'])
# 预处理
def Pretreatment():
noed_nums = 0 # 结点数
node_full = 0 # 树的类型: 1: 满结点为 3 2: 满结点为 7 3: 满结点为 15
for node in nodeList:
if node != flag:
noed_nums += 1
if noed_nums <= 3:
node_full = 3
elif noed_nums <= 7:
node_full = 7
elif noed_nums <= 15:
node_full = 15
return noed_nums, node_full
# 结点数 树的类型
noed_nums, node_full = Pretreatment()
# 结点层数
node_layers = math.log((node_full + 1), 2)
node_layers = (int)(float(node_layers))
# 所有结点 当前结点 当前结点元素 当前nodeList[i]的元素 表示第 i 层堆栈长方块 move_frame 是否已经出现
nodeList_unzip = [*nodeList]
pre_list = nodeList_unzip
count = 1
index_tmp = 0
num_index = 0
stack_i = 0
turn_on = False
# 自定义函数代码(若需更改代码,其行数与格式必须保持一致)
preOrder_codes = [
# "void BinaryLinkList<elemType>::preOrder(Node *t) const",
"void preOrder(Node *t) const",
"{",
" if (t)",
" {",
" cout << t->data << ' ';",
" preOrder(t->left);",
" preOrder(t->right);",
" }",
"}",
]
inOrder_codes = [
# "void BinaryLinkList<elemType>::inOrder(Node *t) const",
"void inOrder(Node *t) const",
"{",
" if (t)",
" {",
" inOrder(t->left);",
" cout << t->data << ' ';",
" inOrder(t->right);",
" }",
"}",
]
postOrder_codes = [
# "void BinaryLinkList<elemType>::postOrder(Node *t) const",
"void postOrder(Node *t) const",
"{",
" if (t)",
" {",
" postOrder(t->left);",
" postOrder(t->right);",
" cout << t->data << ' ';",
" }",
"}",
]
levelOrderTraverse_codes = [
# "void BinaryLinkList<elemType>::levelOrderTraverse() const",
"void levelOrderTraverse() const",
"{",
" queue<Node*> que;",
" Node* p = root;",
" if (p)",
" que.push(p);",
" while (!que.empty())",
" {",
" p = que.front();",
" que.pop();",
" cout << p->data << ' ';",
" if (p->left != NULL)",
" que.push(p->left);",
" if (p->right!= NULL)",
" que.push(p->right);",
" }",
"}",
]
preOrderCreate_codes = [
# "void BinaryLinkList<elemType>::preOrderCreate(elemType flag, Node *&t)",
"void preOrderCreate(elemType flag, Node *&t)",
"{",
" elemType value;",
" cin >> value;",
" if (value!=flag)",
" {",
" t = new Node(value);",
" preOrderCreate(flag, t->left);",
" preOrderCreate(flag, t->right);",
" }",
"}",
]
levelOrderCreate_codes = [
# "void BinaryLinkList<elemType>::levelOrderCreate(elemType flag)"
"void levelOrderCreate(elemType flag)"
"{"
" queue<Node *> que;"
" Node *p;"
" elemType value, ldata, rdata;"
" cin >> value;"
" if (value != flag)"
" root = new Node(value);"
" que.push(root);"
" while (!que.empty())"
" {"
" p = que.front();"
" que.pop();"
" cin >> ldata >> rdata;"
" if (ldata != flag)"
" que.push(p->left = new Node(ldata));"
" if (rdata != flag)"
" que.push(p->right = new Node(rdata));"
" }"
"}"
]
class TreeNode:
def __init__(self, value):
self.value = value
self.leftChild = None
self.rightChild = None
class BiTree:
def __init__(self, pre_list, chose, play):
"""
1: 前序顺序建立二叉树
2: 层次建立二叉树
3: pre_list 按照规定顺序且 pre_list[0] 不能为 '*'(flag)
"""
self.treeNode = TreeNode(None)
self.pre_list = pre_list
if flag == 1:
self.treeNode = self.__preOrderCreate(self.treeNode)
elif flag == 2:
self.treeNode = self.__levelOrderCreate(self.treeNode)
# self.count = 0
def __preOrderCreate(self, node):
value = self.pre_list[0]
if len(self.pre_list) > 1:
self.pre_list = self.pre_list[1:]
if value == flag: # 当遇到 flag 时,令树的根节点为 None,从而结束该分支的递归
node = None
else:
node = TreeNode(value)
node.leftChild = self.__preOrderCreate(node.leftChild)
node.rightChild = self.__preOrderCreate(node.rightChild)
return node
def __levelOrderCreate(self, node):
data = self.pre_list[0]
node = TreeNode(data)
Nodes = [node]
i = 1
for data in Nodes:
if data != None:
data.leftChild = (
TreeNode(self.pre_list[i]) if self.pre_list[i] != flag else None
)
Nodes.append(data.leftChild)
i += 1
if i == len(self.pre_list):
return node
data.rightChild = (
TreeNode(self.pre_list[i]) if self.pre_list[i] != flag else None
)
i += 1
Nodes.append(data.rightChild)
if i == len(self.pre_list):
return node
def preTraverse(self):
"""
前序遍历
"""
self.__preTraverse(self.treeNode)
def __preTraverse(self, node):
if node != None:
print(node.value, end="")
self.__preTraverse(node.leftChild)
self.__preTraverse(node.rightChild)
def midTraverse(self):
"""
中序遍历
"""
self.__midTraverse(self.treeNode)
def __midTraverse(self, node):
if node != None:
self.__midTraverse(node.leftChild)
print(node.value, end="")
self.__midTraverse(node.rightChild)
def postTraverse(self):
"""
后序遍历
"""
self.__postTraverse(self.treeNode)
def __postTraverse(self, node):
if node != None:
self.__postTraverse(node.leftChild)
self.__postTraverse(node.rightChild)
print(node.value, end="")
def levelOrderTraverse(self):
"""
层次遍历
"""
self.__levelOrderTraverse(self.treeNode)
def __levelOrderTraverse(self, node):
if node != None:
pass
queue = []
queue.append(node)
last = node
level = 1
print("Level " + str(level) + ":", end=" ")
while queue:
node = queue.pop(0)
print(node.value, end=" ")
if node.leftChild:
nlast = node.leftChild
queue.append(node.leftChild)
if node.rightChild:
nlast = node.rightChild
queue.append(node.rightChild)
if node == last and queue:
last = nlast
print()
level += 1
print("Level " + str(level) + ":", end=" ")
class Scene_White(Scene):
CONFIG = {"camera_config": {"background_color": WHITE, "use_plot_depth": True,}}
class tree(Scene_White):
def construct(self):
global count, pre_list, index_tmp, num_index, stack_i
# Frame 整体框架
# height: 8 * width: 14.2
frame_code = Rectangle(
color=BLUE, stroke_opacity=0, height=4, width=7.1,
).to_corner(UR, buff=0)
frame_variable = Rectangle(
color=RED, stroke_opacity=0, height=4, width=7.1,
).to_corner(DR, buff=0)
frame_animation = Rectangle(
color="#ffa400",
stroke_width=5,
stroke_opacity=0,
fill_color=WHITE,
fill_opacity=1,
height=8,
width=7.1,
).to_corner(LEFT, buff=0)
self.add(frame_code, frame_variable, frame_animation)
# --------------- 动画框架 ---------------
# 基准圆形
circle_base = Circle(
radius=0.6, stroke_width=8, stroke_color=BLACK, stroke_opacity=1
)
# 基准大小
narrow_multiple = circle_base.get_width() # 直径
# assert circle_base.get_width() * 2 == 1
# 结点集合
base_all = VGroup()
for i in range(node_full):
base_tmp = circle_base.copy()
base_all.add(base_tmp)
# 结点元素集合
element_all = VGroup()
for i in range(len(pre_list)):
element_tmp = Text(pre_list[i], font="江西拙楷", color=BLACK).scale(1.5).copy()
if pre_list[i] != flag:
element_all.add(element_tmp)
# 结点连线集合
line_all = VGroup()
# 各结点的位置
if node_full == 3:
pass
elif node_full == 7:
# 结点 0 的位置
base_all[0].move_to(frame_animation).align_to(frame_animation, UP).shift(
DOWN * 0.8
)
# 结点 1 结点 2 的位置
base_all[1].next_to(base_all[0], DOWN, buff=1).shift(LEFT * 1.5)
# 结点 0 1 连线
base_0 = base_all[0].point_at_angle(250 * DEGREES)
base_1 = base_all[1].point_at_angle(90 * DEGREES)
line_0_1 = Line(
np.array(base_0), np.array(base_1), color=BLACK, stroke_width=5
)
base_all[2].next_to(base_all[0], DOWN, buff=1).shift(RIGHT * 1.5)
# 结点 0 2 连线
base_0 = base_all[0].point_at_angle(290 * DEGREES)
base_2 = base_all[2].point_at_angle(90 * DEGREES)
line_0_2 = Line(
np.array(base_0), np.array(base_2), color=BLACK, stroke_width=5
)
# 结点 3 结点 4 的位置
base_all[3].next_to(base_all[1], DOWN, buff=1).shift(LEFT * 1.2)
# 结点 1 3 连线
base_1 = base_all[1].point_at_angle(240 * DEGREES)
base_3 = base_all[3].point_at_angle(90 * DEGREES)
line_1_3 = Line(
np.array(base_1), np.array(base_3), color=BLACK, stroke_width=5
)
base_all[4].next_to(base_all[1], DOWN, buff=1).shift(RIGHT * 0.7)
# 结点 1 4 连线
base_1 = base_all[1].point_at_angle(290 * DEGREES)
base_4 = base_all[4].point_at_angle(90 * DEGREES)
line_1_4 = Line(
np.array(base_1), np.array(base_4), color=BLACK, stroke_width=5
)
# 结点 5 结点 6 的位置
base_all[5].next_to(base_all[2], DOWN, buff=1).shift(LEFT * 0.7)
# 结点 2 5 连线
base_2 = base_all[2].point_at_angle(250 * DEGREES)
base_5 = base_all[5].point_at_angle(90 * DEGREES)
line_2_5 = Line(
np.array(base_2), np.array(base_5), color=BLACK, stroke_width=5
)
base_all[6].next_to(base_all[2], DOWN, buff=1).shift(RIGHT * 1.2)
# 结点 2 6 连线
base_2 = base_all[2].point_at_angle(300 * DEGREES)
base_6 = base_all[6].point_at_angle(90 * DEGREES)
line_2_6 = Line(
np.array(base_2), np.array(base_6), color=BLACK, stroke_width=5
)
# 集合
line_all = VGroup(
line_0_1, line_0_2, line_1_3, line_1_4, line_2_5, line_2_6
)
elif node_full == 15:
pass
# 代码背景框
background = RoundedRectangle(
stroke_width=1,
stroke_color=GRAY,
fill_color="#EBEBEB",
fill_opacity=0.95,
plot_depth=-1,
corner_radius=0.05,
sheen_factor=0.1,
sheen_direction=UR,
)
background.set_height(3.5, stretch=True).set_width(6.5, stretch=True)
background.move_to(frame_code)
# frame_code 背景 + 代码 + 移动框
class codeline_preOrderCreate(Text):
CONFIG = {
"t2c": {".": WHITE, "t.": BLACK}, # t. 需要和 . 区分开
"size": 0.50,
"color": BLACK,
"font": "Consolas",
}
def __init__(self, text, **kwargs):
Text.__init__(self, text, **kwargs)
class codeline_preOrder(Text):
CONFIG = {
"t2c": {".": WHITE, "t.": BLACK},
"size": 0.65,
"color": BLACK,
"font": "Consolas",
}
def __init__(self, text, **kwargs):
Text.__init__(self, text, **kwargs)
class codeline_inOrder(Text):
CONFIG = {
"t2c": {".": WHITE, "t.": BLACK},
"size": 0.65,
"color": BLACK,
"font": "Consolas",
}
def __init__(self, text, **kwargs):
Text.__init__(self, text, **kwargs)
class codeline_postOrder(Text):
CONFIG = {
"t2c": {".": WHITE, "t.": BLACK},
"size": 0.65,
"color": BLACK,
"font": "Consolas",
}
def __init__(self, text, **kwargs):
Text.__init__(self, text, **kwargs)
def ignore_space_len(code, str, num):
origin_len = len(code)
begin = origin_len - 1
record = 0
if str == "pr":
temp_codes = preOrder_codes
elif str == "in":
temp_codes = inOrder_codes
elif str == "po":
temp_codes = postOrder_codes
elif str == "prC":
temp_codes = preOrderCreate_codes
for index in range(begin, 0, -1):
if temp_codes[num][index] == " " and record == 1:
if str == "pr":
return (origin_len - index - 2) * 0.19
elif str == "in":
return (origin_len - index - 2) * 0.19
elif str == "po":
return (origin_len - index - 2) * 0.19
else:
return (origin_len - index - 2) * 0.14
elif temp_codes[num][index] == " " and record == 0:
record = 1
elif temp_codes[num][index] != " ":
record = 0
if str == "pr":
return origin_len * 0.19
elif str == "in":
return origin_len * 0.19
elif str == "po":
return origin_len * 0.19
else:
return origin_len * 0.14
codes_preOrderCreate = (
VGroup(*[codeline_preOrderCreate(code) for code in preOrderCreate_codes])
.arrange(DOWN, aligned_edge=LEFT, buff=0.05)
.next_to(background.get_top(), DOWN, buff=0)
.shift(LEFT * 0.05 + DOWN * 0.2)
)
codes_preOrder = (
VGroup(*[codeline_preOrder(code) for code in preOrder_codes])
.arrange(DOWN, aligned_edge=LEFT, buff=0.05)
.next_to(background.get_top(), DOWN, buff=0)
.shift(DOWN * 0.2)
)
codes_inOrder = (
VGroup(*[codeline_inOrder(code) for code in inOrder_codes])
.arrange(DOWN, aligned_edge=LEFT, buff=0.05)
.next_to(background.get_top(), DOWN, buff=0)
.shift(DOWN * 0.2)
)
codes_postOrder = (
VGroup(*[codeline_postOrder(code) for code in postOrder_codes])
.arrange(DOWN, aligned_edge=LEFT, buff=0.05)
.next_to(background.get_top(), DOWN, buff=0)
.shift(DOWN * 0.2)
)
# 代码框
# codes_preOrderCreate height: 0.28 * width: 0.1 * x
# codes_preOrder height: 0.35 * width: 0.1 * x
# codes_inOrder height: 0.35 * width: 0.1 * x
# codes_postOrder height: 0.35 * width: 0.1 * x
move_frame = RoundedRectangle(
stroke_width=2.5, stroke_color=BLUE, corner_radius=0.05,
)
# 代码框左边的小三角
arrow = Triangle(stroke_opacity=0, fill_opacity=1, fill_color=RED).rotate(
90 * DEGREES, axis=IN
)
if chose == 1:
arrow.scale(0.11)
else:
arrow.scale(0.13)
# 保存小三角和代码框的相对位置不变
arrow.add_updater(lambda a: a.next_to(move_frame, LEFT, buff=0.1))
# 移动圆环
move_circle = Circle(
radius=0.48, stroke_width=20, stroke_color=BLUE, stroke_opacity=1
).shift(
LEFT * 10
) # 让它换地方消失
self.add(background)
if chose == 1:
self.add(codes_preOrderCreate)
elif chose == 2:
self.add(codes_preOrder)
elif chose == 3:
self.add(codes_inOrder)
elif chose == 4:
self.add(codes_postOrder)
# frame_variable
stack_frame = RoundedRectangle(
stroke_width=8,
stroke_color=GREEN_B,
fill_color="#EBEBEB",
fill_opacity=0,
plot_depth=-1,
corner_radius=0.05,
sheen_factor=0.1,
sheen_direction=UR,
)
stack_frame.set_height(3, stretch=True).set_width(6.5, stretch=True)
stack_frame.move_to(frame_variable).align_to(frame_variable, UP)
stack_location = Text("结点位置", font="思源宋体 Heavy", color=PURPLE).scale(0.7)
stack_father = Text("父结点", font="思源宋体 Heavy", color=ORANGE).scale(0.7)
stack_location.next_to(stack_frame, DOWN, buff=0.1).shift(LEFT * 1.5)
stack_father.next_to(stack_frame, DOWN, buff=0.1).shift(RIGHT * 1.5)
stack_level = Text("结点层数", font="思源宋体 Heavy", color=PURPLE).scale(0.7)
stack_value = Text("结点值", font="思源宋体 Heavy", color=ORANGE).scale(0.7)
stack_level.next_to(stack_frame, DOWN, buff=0.1).shift(LEFT * 1.5)
stack_value.next_to(stack_frame, DOWN, buff=0.1).shift(RIGHT * 1.5)
self.add(stack_frame)
# 堆栈长方块
base_stack = RoundedRectangle(
stroke_width=5.5,
stroke_color="FF5900",
fill_color=BLUE,
fill_opacity=0.95,
plot_depth=-1,
corner_radius=0.05,
sheen_factor=0.15,
sheen_direction=UR,
)
base_stack.set_height(0.6, stretch=True).set_width(6.36, stretch=True)
# 堆栈长方块中的 方向 和 父结点
left_direction = (
Text("左", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
right_direction = (
Text("右", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
origin_direction = (
Text("中", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
bottom_father = (
Text("NULL", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_father = (
Text("A", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
# 堆栈长方块整体
base_stack_all = VGroup(base_stack, left_direction, tmp_father)
# 堆栈长方块(bottom)
stack_bottom = VGroup(base_stack, origin_direction, bottom_father)
# 堆栈长方块(top)
stack_top = RoundedRectangle(
stroke_opacity=0,
fill_color=YELLOW_D,
fill_opacity=0.95,
corner_radius=0.05,
sheen_factor=0.1,
sheen_direction=UR,
)
stack_top.set_height(0.315, stretch=True).set_width(6.42, stretch=True)
# 堆栈长方块(top)里面的小三角
arrow_in = (
Triangle(stroke_opacity=0, fill_opacity=1, fill_color=GREEN_E)
.scale(0.1)
.rotate(180 * DEGREES, axis=IN)
)
# 堆栈长方块集合
""" 前序顺序建立二叉树 专属
stack_all -> 除外 bottom 和 top 外的其他全部堆栈长方块
|
├─ stack_layers -> 每一层的堆栈长方块
| |_ tmp_stack_all -> 一层中的一种类型的堆栈长方块
| ├─ base_stack -> 堆栈长方块的外型
| ├─ left_direction -> 堆栈长方块的方向(左)变量
| |_ tmp_father -> 堆栈长方块的父结点值(右)变量
|
├─ stack_layers
| |_ tmp_stack_all X 2
|
|_ stack_layers
|_ tmp_stack_all X 4
"""
if chose == 1:
stack_all = VGroup()
for layer in range(node_layers):
stack_layers = VGroup()
stack_all.add(stack_layers)
def prC(self):
global pre_list, stack_i
value = pre_list[0]
if len(pre_list) > 1:
pre_list = pre_list[1:]
if value == flag: # 当遇到 flag 时,令树的根节点为 None,从而结束该分支的递归
return
else:
tmp_father = (
Text(value, font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, left_direction, tmp_father)
stack_all[stack_i].add(tmp_stack_all.copy())
stack_i += 1
prC(self)
prC(self)
stack_i -= 1
prC(self)
pre_list = nodeList_unzip # 恢复 pre_list
stack_i = 0 # 恢复 stack_i
""" 前序遍历二叉树 | 中序遍历二叉树 | 后序遍历二叉树 专属
string_Traverse -> 遍历的字符串
stack_all -> 除外 bottom 和 top 外的其他全部堆栈长方块
|
├─ stack_layers -> 每一层的堆栈长方块
| |_ tmp_stack_all -> 一层中的一种类型的堆栈长方块
| ├─ base_stack -> 堆栈长方块的外型
| ├─ tmp_layer -> 堆栈长方块的层数(左)变量
| |_ tmp_value -> 堆栈长方块的结点值(右)变量
|
├─ stack_layers
| |_ tmp_stack_all X 2
|
|_ stack_layers
| |_ tmp_stack_all X 4
|
|_ stack_layers
|_ tmp_stack_all X 8 -> 特殊(结点值为 NULL)的一层中的堆栈长方块
"""
if chose == 2 or chose == 3 or chose == 4:
stack_all = VGroup()
string_Traverse = ""
for layer in range(node_layers + 1):
stack_layers = VGroup()
stack_all.add(stack_layers)
class T_N:
def __init__(self, value):
self.value = value
self.leftChild = None
self.rightChild = None
def prC(node):
global pre_list
value = pre_list[0]
if len(pre_list) > 1:
pre_list = pre_list[1:]
if value == flag: # 当遇到 flag 时,令树的根节点为 None,从而结束该分支的递归
node = None
else:
node = T_N(value)
node.leftChild = prC(node.leftChild)
node.rightChild = prC(node.rightChild)
return node
def pr(node):
nonlocal string_Traverse
global stack_i
if node != None:
# 结点层数 stack_i+1 结点值 node.value
string_Traverse += node.value
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text(node.value, font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
stack_i += 1
pr(node.leftChild)
pr(node.rightChild)
stack_i -= 1
else:
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text("NULL", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
def In(node):
nonlocal string_Traverse
global stack_i
if node != None:
# 结点层数 stack_i+1 结点值 node.value
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text(node.value, font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
stack_i += 1
In(node.leftChild)
string_Traverse += node.value
In(node.rightChild)
stack_i -= 1
else:
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text("NULL", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
def po(node):
nonlocal string_Traverse
global stack_i
if node != None:
# 结点层数 stack_i+1 结点值 node.value
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text(node.value, font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
stack_i += 1
po(node.leftChild)
po(node.rightChild)
string_Traverse += node.value
stack_i -= 1
else:
tmp_layer = (
Text(str(stack_i + 1), font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(LEFT * 1.5)
)
tmp_value = (
Text("NULL", font="思源宋体 Heavy", color=BLACK)
.scale(0.7)
.move_to(base_stack)
.align_to(base_stack)
.shift(RIGHT * 1.5)
)
tmp_stack_all = VGroup(base_stack, tmp_layer, tmp_value)
stack_all[stack_i].add(tmp_stack_all.copy())
tmp_treeNode = T_N(None)
treeNode = prC(tmp_treeNode)
if chose == 2:
pr(treeNode)
elif chose == 3:
In(treeNode)
elif chose == 4:
po(treeNode)
pre_list = nodeList_unzip # 恢复 pre_list
stack_i = 0 # 恢复 stack_i
# 各堆栈长方块的位置
sort_stack_all = VGroup()
for sort_stack in stack_all:
sort_stack_all.add(sort_stack[0])
sort_stack_all.arrange(UP, aligned_edge=LEFT, buff=0.05)
if chose == 1:
stack_bottom.move_to(stack_frame).align_to(stack_frame, DOWN).shift(
UP * 0.065
)
sort_stack_all.move_to(stack_bottom).next_to(
stack_bottom, UP, buff=0
).shift(UP * 0.05)
else:
sort_stack_all.move_to(stack_frame).align_to(stack_frame, DOWN).shift(
UP * 0.065
)
for sort_stacks in stack_all:
for sort_stack in sort_stacks:
if sort_stack != sort_stacks[0]:
sort_stack.move_to(sort_stacks[0])
stack_top.move_to(stack_frame).align_to(stack_frame, DOWN).shift(
UP * 0.04
) # .shift(UP*0.65*4)
# 保存小三角和堆栈长方块(top)的相对位置不变
arrow_in.add_updater(lambda a: a.move_to(stack_top))
# self.add(sort_stack_all, stack_bottom, stack_top, arrow_in)
# frame_animation
# 位于框架下面的 Value 和 剩余串(前序顺序建立二叉树 专属)
"""
animation_value_string -> 原字符串
animation_value -> Value 整体
|
├─ animation_value_reveal -> Value 左边部分(显示的 Value)
|_ animation_value_value -> Value 右边部分(Value 的结点值)
animation_string -> 剩余串 整体
|
├─ animation_string_reveal -> 剩余串 左边部分(显示的 剩余串)
|_ animation_string_value -> 剩余串 右边部分(剩余串 的字符串)
"""
animation_value_string = nodeList
animation_value_reveal = Text("Value:", font="思源宋体 Heavy", color=GOLD).scale(
0.7
)
animation_string_reveal = Text("剩余串:", font="思源宋体 Heavy", color=BLUE).scale(0.7)
animation_value_value = Text(".", font="思源宋体 Heavy", color=WHITE).scale(0.7)
animation_string_value = Text(
animation_value_string, font="思源宋体 Heavy", color=BLACK
).scale(0.7)
animation_value_reveal.align_to(frame_animation, LEFT).align_to(
frame_animation, DOWN
).shift(UP * 0.6 + RIGHT * 0.4)
animation_value_value.next_to(animation_value_reveal, RIGHT, buff=0.15)
animation_string_reveal.align_to(frame_animation, DOWN).next_to(
animation_value_reveal, RIGHT, buff=0.8
)
animation_string_value.next_to(animation_string_reveal, RIGHT, buff=0.15)
animation_value = VGroup(animation_value_reveal, animation_value_value)
animation_string = VGroup(animation_string_reveal, animation_string_value)
# 位于框架下面的 遍历结点 (前序遍历二叉树 | 中序遍历二叉树 | 后序遍历二叉树 专属)
"""
animation_value_stringTraverse -> 遍历的字符串
animation_stringTraverse -> 遍历结点 整体
|
├─ animation_stringTraverse_reveal -> 遍历结点 左边部分(显示的 遍历结点)
|_ animation_stringTraverse_value -> 遍历结点 右边部分(遍历结点 的各个结点值)
"""
animation_value_stringTraverse = (
string_Traverse if chose != 1 else nodeList
) # 为了防止被 chose==1 的情况影响
animation_stringTraverse_reveal = Text(
"遍历结果:", font="思源宋体 Heavy", color=GOLD
).scale(0.7)
animation_stringTraverse_reveal.align_to(frame_animation, LEFT).align_to(
frame_animation, DOWN
).shift(UP * 0.6 + RIGHT * 1)
animation_stringTraverse_value = VGroup()
index_Traverse = 0
for stringTraverse_value in animation_value_stringTraverse:
stringTraverse_reveal_tmp = Text(
stringTraverse_value, font="思源宋体 Heavy", color=BLACK
).scale(0.7)
if stringTraverse_value == animation_value_stringTraverse[0]:
stringTraverse_reveal_tmp.next_to(
animation_stringTraverse_reveal, RIGHT, buff=0.25
)
else:
stringTraverse_reveal_tmp.move_to(
animation_stringTraverse_value[index_Traverse]
)
index_Traverse += 1
stringTraverse_reveal_tmp.shift(RIGHT * 0.5)
animation_stringTraverse_value.add(stringTraverse_reveal_tmp)
animation_stringTraverse = VGroup(
animation_stringTraverse_reveal, animation_stringTraverse_value
)
# 二叉树结点
class TreeNode:
def __init__(self, value):
self.value = value
self.leftChild = None
self.rightChild = None
# 前序顺序建立二叉树
def __preOrderCreate(node):
global count, pre_list, index_tmp, num_index, stack_i
value = pre_list[0]
if len(pre_list) > 1:
pre_list = pre_list[1:]
if value == nodeList_unzip[0]:
move_frame.set_width(