Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5dc2289

Browse files
committed
0094 Solved
1 parent c713a7b commit 5dc2289

File tree

4 files changed

+114
-0
lines changed

4 files changed

+114
-0
lines changed
3.06 MB
Binary file not shown.
4.94 MB
Loading[フレーム]
10.5 MB
Loading[フレーム]
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
## LeetCode 第 94 号问题:二叉树的中序遍历
2+
3+
> 本文首发于公众号「图解面试算法」,是 [图解 LeetCode ](<https://github.com/MisterBooo/LeetCodeAnimation>) 系列文章之一。
4+
>
5+
> 同步博客:https://www.algomooc.com
6+
7+
题目来源于 LeetCode 上第 94 号问题:二叉树的中序遍历。题目难度为 Medium
8+
9+
### 题目描述
10+
11+
给定一个二叉树,返回它的 **中序** 遍历.
12+
13+
#### 示例:
14+
15+
```cassandra
16+
输入: [1,null,2,3]
17+
1
18+
\
19+
2
20+
/
21+
3
22+
23+
输出: [1,3,2]
24+
```
25+
26+
**进阶:** 递归算法很简单,你可以通过迭代算法完成吗?
27+
28+
### 题目解析
29+
30+
#### 第一种方法: 递归
31+
32+
二叉树的中序遍历相信大家已经很熟悉了.操作流程就是 **左 -> 打印 -> 右**.
33+
34+
那就按照 **左 -> 打印 -> 右** 这种顺序遍历树就可以了,递归函数实现
35+
36+
- 终止条件:当前节点为空时
37+
- 函数内: 递归的调用左节点,打印当前节点,再递归调用右节点
38+
39+
##### 参考代码
40+
41+
```javascript
42+
// lang=javascript
43+
var inorderTraversal = function(root) {
44+
let res = [];
45+
handle(root,res);
46+
return res;
47+
};
48+
function handle(root, res) {
49+
if (root !== null) {
50+
handle(root.left, res);
51+
res.push(root.val);
52+
handle(root.right, res);
53+
}
54+
}
55+
```
56+
57+
##### 复杂度分析
58+
59+
- 时间复杂度: O(n),
60+
- 空间复杂度: O(h),h是树的高度
61+
62+
#### 第二种方法: 迭代
63+
64+
这题的真正难点在于如何用非递归的方式实现。
65+
66+
递归的调用过程是不断往左边走,当左边走不下去了,就打印节点,并转向右边,然后右边继续这个过程,是函数自己调用自己,一层层的嵌套下去,操作系统/虚拟机自动帮我们用 ****来保存了每个调用的函数,现在我们需要自己模拟这样的调用过程。
67+
68+
栈的特性是**后进先出**, 那么我们将遍历左子树的节点压栈, 当找不到左子树时, 栈顶就是最底层的左子树, 出栈打印出来; 接着转向右子树父节点, 继续遍历父节点的左子树并压栈,循环如此.
69+
70+
因此遍历的过程就是:
71+
72+
1. 压栈根节点
73+
2. 遍历左子树, 压栈, 直到左子树为空
74+
3. 出栈栈顶元素, 打印
75+
4. 转向右子树, 重复 1, 2, 3步骤
76+
77+
##### 动画理解
78+
79+
<img src="../Animation/Animation2.gif" alt="Animation2" style="zoom:150%;" />
80+
81+
##### 参考代码
82+
83+
```javascript
84+
// lang=javascript
85+
var inorderTraversal = function(root) {
86+
let res = [],
87+
stack = [],
88+
node = root;
89+
while (stack.length > 0 || node !== null) {
90+
while (node) {
91+
stack.push(node);
92+
node = node.left;
93+
}
94+
node = stack.pop();
95+
res.push(node.val);
96+
node = node.right;
97+
}
98+
return res;
99+
}
100+
```
101+
102+
##### 复杂度分析
103+
104+
- 时间复杂度:O(n)
105+
- 空间复杂度:O(n)
106+
107+
![qrcode](../../Pictures/qrcode.jpg)
108+
109+
110+
111+
112+
113+
114+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /