Skip to content

Commit 382f102

Browse files
committed
前序遍历
1 parent 0702b3f commit 382f102

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

数据结构/二叉树/二叉树.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
二叉树是一种常见的数据结构,每个节点最多拥有两个子树,分别称为左子树和右子树。
2+
3+
### 二叉树的遍历
4+
> 重点知识,需要熟练掌握二叉树的前序、中序和后序遍历的递归、迭代书写
5+
6+
- [二叉树的前序遍历](./二叉树的前序遍历.md)
7+
- 中序遍历
8+
- 后序遍历
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
```

0 commit comments

Comments
 (0)