Skip to content

Commit c7a0383

Browse files
committed
add LeetCode 144. 二叉树的前序遍历
1 parent 4786b6e commit c7a0383

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

Diff for: 二叉树/LeetCode 144. 二叉树的前序遍历.md

+111
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给定一个二叉树,返回它的 前序 遍历。
6+
7+
示例:
8+
9+
```javascript
10+
输入: [1,null,2,3]
11+
1
12+
\
13+
2
14+
/
15+
3
16+
17+
输出: [1,2,3]
18+
```
19+
20+
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
21+
22+
来源:力扣(LeetCode)
23+
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
24+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
25+
26+
27+
28+
29+
## 解题思路
30+
31+
**递归解法**
32+
33+
```javascript
34+
/**
35+
* Definition for a binary tree node.
36+
* function TreeNode(val) {
37+
* this.val = val;
38+
* this.left = this.right = null;
39+
* }
40+
*/
41+
/**
42+
* @param {TreeNode} root
43+
* @return {number[]}
44+
*/
45+
var preorderTraversal = function (root) {
46+
if (!root) return [];
47+
let res = [];
48+
let fun = (root) => {
49+
if (root) res.push(root.val);
50+
root.left && fun(root.left);
51+
root.right && fun(root.right);
52+
}
53+
fun(root);
54+
return res;
55+
};
56+
```
57+
58+
**迭代做法**
59+
60+
```javascript
61+
/**
62+
* Definition for a binary tree node.
63+
* function TreeNode(val) {
64+
* this.val = val;
65+
* this.left = this.right = null;
66+
* }
67+
*/
68+
/**
69+
* @param {TreeNode} root
70+
* @return {number[]}
71+
*/
72+
var preorderTraversal = function (root) {
73+
if (!root) return [];
74+
let res = [];
75+
let queue = [root];
76+
while (queue.length) {
77+
let size = queue.length;
78+
while (size--) {
79+
// 取左孩子
80+
let node = queue.pop();
81+
res.push(node.val);
82+
// 优先放右孩子
83+
node.right && queue.push(node.right);
84+
node.left && queue.push(node.left);
85+
}
86+
}
87+
return res;
88+
};
89+
```
90+
91+
## 最后
92+
文章产出不易,还望各位小伙伴们支持一波!
93+
94+
往期精选:
95+
96+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
97+
98+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
99+
100+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
101+
102+
103+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
104+
105+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
106+
107+
```javascript
108+
学如逆水行舟,不进则退
109+
```
110+
111+

0 commit comments

Comments
 (0)