File tree Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Expand file tree Collapse file tree 2 files changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ 二叉树是一种常见的数据结构,每个节点最多拥有两个子树,分别称为左子树和右子树。
2
+
3
+ ### 二叉树的遍历
4
+ > 重点知识,需要熟练掌握二叉树的前序、中序和后序遍历的递归、迭代书写
5
+
6
+ - [ 二叉树的前序遍历] ( ./二叉树的前序遍历.md )
7
+ - 中序遍历
8
+ - 后序遍历
Original file line number Diff line number Diff line change
1
+ ### 题目
2
+ 给定一个二叉树,返回它的 前序 遍历。
3
+
4
+ 示例:
5
+ ``` js
6
+ 输入: [1 ,null ,2 ,3 ]
7
+ 1
8
+ \
9
+ 2
10
+ /
11
+ 3
12
+
13
+ 输出: [1 ,2 ,3 ]
14
+ ```
15
+
16
+ ## 代码
17
+ 递归版本
18
+
19
+ ``` js
20
+ function preorderTraversal (root ) {
21
+ const arr = []
22
+ preorder (root, arr)
23
+ return arr
24
+ }
25
+ function perorder (node , arr ) {
26
+ if (node) {
27
+ arr .push (node .val )
28
+ preorder (node .left , arr)
29
+ preorder (node .right , arr)
30
+ }
31
+ }
32
+ ```
33
+
34
+ 迭代版本:
35
+ 1 . 取根节点入栈
36
+ 2 . 取节点的左子节点入栈,直到左子节点为空
37
+ 3 . 节点出栈,取右节点入栈,重复 1,2,3直到节点和栈都为空
38
+
39
+ ``` js
40
+ function preorderTraversal (root ) {
41
+ let stack = []
42
+ let res = []
43
+ let now = root
44
+
45
+ while (now || stack .length > 0 ) {
46
+ if (now) {
47
+ res .push (now .val )
48
+ stack .push (now)
49
+ now = now .left
50
+ }else {
51
+ now = stack .pop ()
52
+ now = now .right
53
+ }
54
+ }
55
+
56
+ return res
57
+ }
58
+
59
+ ```
You can’t perform that action at this time.
0 commit comments