File tree Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change
1
+ const binaryTree = {
2
+ val : "A" ,
3
+ left : {
4
+ val : "B" ,
5
+ left : {
6
+ val : "D"
7
+ } ,
8
+ right : {
9
+ val : "E"
10
+ }
11
+ } ,
12
+ right : {
13
+ val : "C" ,
14
+ right : {
15
+ val : "F"
16
+ }
17
+ }
18
+ } ;
19
+
20
+ /**
21
+ * 前序遍历 访问顺序为 根节点 -> 左节点 -> 右节点
22
+ */
23
+ function preorder ( root ) {
24
+ // 递归边界,root 为空
25
+ if ( ! root ) {
26
+ return ;
27
+ }
28
+
29
+ // 输出当前遍历的结点值
30
+ console . log ( "当前遍历的结点值是:" , root . val ) ;
31
+ // 递归遍历左子树
32
+ preorder ( root . left ) ;
33
+ // 递归遍历右子树
34
+ preorder ( root . right ) ;
35
+ }
36
+
37
+ /**
38
+ * 中序遍历 访问顺序为 左节点 -> 根节点 -> 右节点
39
+ */
40
+ function inorder ( root ) {
41
+ // 递归边界,root 为空
42
+ if ( ! root ) {
43
+ return ;
44
+ }
45
+
46
+ // 递归遍历左子树
47
+ inorder ( root . left ) ;
48
+ // 输出当前遍历的结点值
49
+ console . log ( "当前遍历的结点值是:" , root . val ) ;
50
+ // 递归遍历右子树
51
+ inorder ( root . right ) ;
52
+ }
53
+
54
+ /**
55
+ * 后序遍历 访问顺序为 左节点 -> 右节点 -> 根节点
56
+ */
57
+ function postorder ( root ) {
58
+ // 递归边界,root 为空
59
+ if ( ! root ) {
60
+ return ;
61
+ }
62
+
63
+ // 递归遍历左子树
64
+ postorder ( root . left ) ;
65
+ // 递归遍历右子树
66
+ postorder ( root . right ) ;
67
+ // 输出当前遍历的结点值
68
+ console . log ( "当前遍历的结点值是:" , root . val ) ;
69
+ }
70
+
71
+ console . log ( "前序遍历" ) ;
72
+ preorder ( binaryTree ) ;
73
+
74
+ console . log ( "中序遍历" ) ;
75
+ inorder ( binaryTree ) ;
76
+
77
+ console . log ( "后序遍历" )
78
+ postorder ( binaryTree )
You can’t perform that action at this time.
0 commit comments