@@ -81,7 +81,7 @@ if (root == NULL) return root;
8181
82823 . 确定单层递归的逻辑
8383
84- 因为是先前序遍历 ,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。
84+ 因为是前序遍历 ,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。
8585
8686``` cpp
8787swap (root->left, root->right);
@@ -348,14 +348,13 @@ class Solution:
348348 while stack:
349349 node = stack.pop()
350350 node.left, node.right = node.right, node.left
351+ if node.right:
352+ stack.append(node.right)
351353 if node.left:
352354 stack.append(node.left)
353- if node.right:
354- stack.append(node.right)
355355 return root
356356```
357357
358-
359358递归法:中序遍历:
360359``` python
361360# Definition for a binary tree node.
@@ -374,7 +373,7 @@ class Solution:
374373 return root
375374```
376375
377- 迭代法:中序遍历 :
376+ 迭代法,伪中序遍历(结果是对的,看起来像是中序遍历,实际上它是前序遍历,只不过把中间节点处理逻辑放到了中间。还是要用'统一写法'才是真正的中序遍历) :
378377``` python
379378# Definition for a binary tree node.
380379# class TreeNode:
@@ -386,18 +385,17 @@ class Solution:
386385 def invertTree (self , root : TreeNode) -> TreeNode:
387386 if not root:
388387 return None
389- stack = [root]
388+ stack = [root]
390389 while stack:
391- node = stack.pop()
392- if node.left :
393- stack.append(node.left )
394- node.left, node.right = node.right, node.left
395- if node.left :
396- stack.append(node.left)
390+ node = stack.pop()
391+ if node.right :
392+ stack.append(node.right )
393+ node.left, node.right = node.right, node.left # 放到中间,依然是前序遍历
394+ if node.right :
395+ stack.append(node.right)
397396 return root
398397```
399398
400-
401399递归法:后序遍历:
402400``` python
403401# Definition for a binary tree node.
@@ -416,7 +414,7 @@ class Solution:
416414 return root
417415```
418416
419- 迭代法:后序遍历 :
417+ 迭代法,伪后序遍历(结果是对的,看起来像是后序遍历,实际上它是前序遍历,只不过把中间节点处理逻辑放到了最后。还是要用'统一写法'才是真正的后序遍历) :
420418``` python
421419# Definition for a binary tree node.
422420# class TreeNode:
@@ -427,23 +425,19 @@ class Solution:
427425class Solution :
428426 def invertTree (self , root : TreeNode) -> TreeNode:
429427 if not root:
430- return None
431- stack = [root]
428+ return None
429+ stack = [root]
432430 while stack:
433- node = stack.pop()
431+ node = stack.pop()
432+ if node.right:
433+ stack.append(node.right)
434434 if node.left:
435435 stack.append(node.left)
436- if node.right:
437- stack.append(node.right)
438436 node.left, node.right = node.right, node.left
439437
440438 return root
441439```
442440
443-
444-
445-
446-
447441迭代法:广度优先遍历(层序遍历):
448442``` python
449443# Definition for a binary tree node.
0 commit comments