58
58
59
59
<p ><strong >进阶:</strong > 递归算法很简单,你可以通过迭代算法完成吗?</p >
60
60
61
-
62
61
## 解法
63
62
64
63
<!-- 这里可写通用的实现逻辑 -->
65
64
66
- 递归遍历或利用栈实现非递归遍历。
65
+ ** 1. 递归遍历**
66
+
67
+ 先递归左子树,再访问根节点,接着递归右子树。
68
+
69
+ ** 2. 栈实现非递归遍历**
67
70
68
71
非递归的思路如下:
69
72
72
75
3 . 左节点为空时,弹出栈顶元素并处理
73
76
4 . 重复 2-3 的操作
74
77
78
+ ** 3. Morris 实现前序遍历**
79
+
80
+ Morris 遍历无需使用栈,空间复杂度为 O(1)。核心思想是:
81
+
82
+ 遍历二叉树节点,
83
+
84
+ 1 . 若当前节点 root 的左子树为空,** 将当前节点值添加至结果列表 res** 中,并将当前节点更新为 ` root.right `
85
+ 2 . 若当前节点 root 的左子树不为空,找到左子树的最右节点 pre(也即是 root 节点在中序遍历下的前驱节点):
86
+ - 若前驱节点 pre 的右子树为空,将前驱节点的右子树指向当前节点 root,并将当前节点更新为 ` root.left ` 。
87
+ - 若前驱节点 pre 的右子树不为空,** 将当前节点值添加至结果列表 res** 中,然后将前驱节点右子树指向空(即解除 pre 与 root 的指向关系),并将当前节点更新为 ` root.right ` 。
88
+ 3 . 循环以上步骤,直至二叉树节点为空,遍历结束。
89
+
75
90
<!-- tabs:start -->
76
91
77
92
### ** Python3**
89
104
# self.right = right
90
105
class Solution :
91
106
def inorderTraversal (self , root : TreeNode) -> List[int ]:
107
+ res = []
108
+
92
109
def inorder (root ):
93
110
if root:
94
111
inorder(root.left)
95
112
res.append(root.val)
96
113
inorder(root.right)
97
- res = []
114
+
98
115
inorder(root)
99
116
return res
100
117
```
101
118
102
- 非递归 :
119
+ 栈实现非递归 :
103
120
104
121
``` python
105
122
# Definition for a binary tree node.
@@ -110,8 +127,7 @@ class Solution:
110
127
# self.right = right
111
128
class Solution :
112
129
def inorderTraversal (self , root : TreeNode) -> List[int ]:
113
- s = []
114
- res = []
130
+ res, s = [], []
115
131
while root or s:
116
132
if root:
117
133
s.append(root)
@@ -123,6 +139,36 @@ class Solution:
123
139
return res
124
140
```
125
141
142
+ Morris 遍历:
143
+
144
+ ``` python
145
+ # Definition for a binary tree node.
146
+ # class TreeNode:
147
+ # def __init__(self, val=0, left=None, right=None):
148
+ # self.val = val
149
+ # self.left = left
150
+ # self.right = right
151
+ class Solution :
152
+ def inorderTraversal (self , root : TreeNode) -> List[int ]:
153
+ res = []
154
+ while root:
155
+ if root.left is None :
156
+ res.append(root.val)
157
+ root = root.right
158
+ else :
159
+ pre = root.left
160
+ while pre.right and pre.right != root:
161
+ pre = pre.right
162
+ if pre.right is None :
163
+ pre.right = root
164
+ root = root.left
165
+ else :
166
+ res.append(root.val)
167
+ pre.right = None
168
+ root = root.right
169
+ return res
170
+ ```
171
+
126
172
### ** Java**
127
173
128
174
<!-- 这里可写当前语言的特殊实现逻辑 -->
@@ -146,26 +192,23 @@ class Solution:
146
192
* }
147
193
*/
148
194
class Solution {
149
-
150
- private List<Integer > res;
151
-
152
195
public List<Integer > inorderTraversal (TreeNode root ) {
153
- res = new ArrayList<> ();
154
- inorder(root);
196
+ List< Integer > res = new ArrayList<> ();
197
+ inorder(root, res );
155
198
return res;
156
199
}
157
200
158
- private void inorder (TreeNode root ) {
201
+ private void inorder (TreeNode root , List< Integer > res ) {
159
202
if (root != null ) {
160
- inorder(root. left);
203
+ inorder(root. left, res );
161
204
res. add(root. val);
162
- inorder(root. right);
205
+ inorder(root. right, res );
163
206
}
164
207
}
165
208
}
166
209
```
167
210
168
- 非递归 :
211
+ 栈实现非递归 :
169
212
170
213
``` java
171
214
/**
@@ -185,63 +228,215 @@ class Solution {
185
228
*/
186
229
class Solution {
187
230
public List<Integer > inorderTraversal (TreeNode root ) {
188
- if (root == null ) {
189
- return Collections . emptyList();
190
- }
191
231
List<Integer > res = new ArrayList<> ();
192
- Deque<TreeNode > s = new ArrayDeque <> ();
232
+ Deque<TreeNode > s = new LinkedList <> ();
193
233
while (root != null || ! s. isEmpty()) {
194
234
if (root != null ) {
195
- s. push (root);
235
+ s. offerLast (root);
196
236
root = root. left;
197
237
} else {
198
- root = s. pop();
238
+ root = s. pollLast();
239
+ res. add(root. val);
240
+ root = root. right;
241
+ }
242
+ }
243
+ return res;
244
+ }
245
+ }
246
+ ```
247
+
248
+ Morris 遍历:
249
+
250
+ ``` java
251
+ /**
252
+ * Definition for a binary tree node.
253
+ * public class TreeNode {
254
+ * int val;
255
+ * TreeNode left;
256
+ * TreeNode right;
257
+ * TreeNode() {}
258
+ * TreeNode(int val) { this.val = val; }
259
+ * TreeNode(int val, TreeNode left, TreeNode right) {
260
+ * this.val = val;
261
+ * this.left = left;
262
+ * this.right = right;
263
+ * }
264
+ * }
265
+ */
266
+ class Solution {
267
+ public List<Integer > inorderTraversal (TreeNode root ) {
268
+ List<Integer > res = new ArrayList<> ();
269
+ while (root != null ) {
270
+ if (root. left == null ) {
199
271
res. add(root. val);
200
272
root = root. right;
273
+ } else {
274
+ TreeNode pre = root. left;
275
+ while (pre. right != null && pre. right != root) {
276
+ pre = pre. right;
277
+ }
278
+ if (pre. right == null ) {
279
+ pre. right = root;
280
+ root = root. left;
281
+ } else {
282
+ res. add(root. val);
283
+ pre. right = null ;
284
+ root = root. right;
285
+ }
201
286
}
202
287
}
203
288
return res;
204
289
}
205
290
}
206
291
```
292
+
207
293
### ** JavaScript**
208
294
209
295
递归:
210
296
211
297
``` js
212
- var inorderTraversal = function (root ) {
213
- let res = [];
214
- function inorder (root ){
215
- if (root){
216
- inorder (root .left );
217
- res .push (root .val );
218
- inorder (root .right );
219
- }
298
+ /**
299
+ * Definition for a binary tree node.
300
+ * function TreeNode(val, left, right) {
301
+ * this.val = (val===undefined ? 0 : val)
302
+ * this.left = (left===undefined ? null : left)
303
+ * this.right = (right===undefined ? null : right)
304
+ * }
305
+ */
306
+ /**
307
+ * @param {TreeNode} root
308
+ * @return {number[]}
309
+ */
310
+ var inorderTraversal = function (root ) {
311
+ let res = [];
312
+ function inorder (root ) {
313
+ if (root) {
314
+ inorder (root .left );
315
+ res .push (root .val );
316
+ inorder (root .right );
220
317
}
221
- inorder (root);
222
- return res;
318
+ }
319
+ inorder (root);
320
+ return res;
223
321
};
224
322
```
225
- 非递归:
323
+
324
+ 栈实现非递归:
226
325
227
326
``` js
327
+ /**
328
+ * Definition for a binary tree node.
329
+ * function TreeNode(val, left, right) {
330
+ * this.val = (val===undefined ? 0 : val)
331
+ * this.left = (left===undefined ? null : left)
332
+ * this.right = (right===undefined ? null : right)
333
+ * }
334
+ */
335
+ /**
336
+ * @param {TreeNode} root
337
+ * @return {number[]}
338
+ */
228
339
var inorderTraversal = function (root ) {
229
- let res = [], stk = [];
230
- let cur = root;
231
- while (cur || stk .length !== 0 ) {
232
- while (cur) {
233
- stk .push (cur);
234
- cur = cur .left ;
235
- }
236
- let top = stk .pop ();
237
- res .push (top .val );
238
- cur = top .right ;
340
+ let res = [];
341
+ let s = [];
342
+ while (root || s .length > 0 ) {
343
+ if (root) {
344
+ s .push (root);
345
+ root = root .left ;
346
+ } else {
347
+ root = s .pop ();
348
+ res .push (root .val );
349
+ root = root .right ;
350
+ }
351
+ }
352
+ return res;
353
+ };
354
+ ```
239
355
356
+ ### ** C++**
357
+
358
+ ``` cpp
359
+ /* *
360
+ * Definition for a binary tree node.
361
+ * struct TreeNode {
362
+ * int val;
363
+ * TreeNode *left;
364
+ * TreeNode *right;
365
+ * TreeNode() : val(0), left(nullptr), right(nullptr) {}
366
+ * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
367
+ * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
368
+ * };
369
+ */
370
+ class Solution {
371
+ public:
372
+ vector<int > inorderTraversal(TreeNode* root) {
373
+ vector<int > res;
374
+ while (root)
375
+ {
376
+ if (root->left == nullptr)
377
+ {
378
+ res.push_back(root->val);
379
+ root = root->right;
380
+ } else {
381
+ TreeNode* pre = root->left;
382
+ while (pre->right && pre->right != root)
383
+ {
384
+ pre = pre->right;
385
+ }
386
+ if (pre->right == nullptr)
387
+ {
388
+ pre->right = root;
389
+ root = root->left;
390
+ }
391
+ else
392
+ {
393
+ res.push_back(root->val);
394
+ pre->right = nullptr;
395
+ root = root->right;
396
+ }
397
+ }
398
+ }
399
+ return res;
240
400
}
241
- return res;
242
401
};
243
402
```
244
403
404
+ ### **Go**
405
+
406
+ ```go
407
+ /**
408
+ * Definition for a binary tree node.
409
+ * type TreeNode struct {
410
+ * Val int
411
+ * Left *TreeNode
412
+ * Right *TreeNode
413
+ * }
414
+ */
415
+ func inorderTraversal(root *TreeNode) []int {
416
+ var res []int
417
+ for root != nil {
418
+ if root.Left == nil {
419
+ res = append(res, root.Val)
420
+ root = root.Right
421
+ } else {
422
+ pre := root.Left
423
+ for pre.Right != nil && pre.Right != root {
424
+ pre = pre.Right
425
+ }
426
+ if pre.Right == nil {
427
+ pre.Right = root
428
+ root = root.Left
429
+ } else {
430
+ res = append(res, root.Val)
431
+ pre.Right = nil
432
+ root = root.Right
433
+ }
434
+ }
435
+ }
436
+ return res
437
+ }
438
+ ```
439
+
245
440
### ** ...**
246
441
247
442
```
0 commit comments