如何以简单难忘的方式记住中序遍历和预序遍历?

问题描述

前序遍历、中序遍历、后序遍历、层序遍历等二叉树遍历是很多 IT 公司经常面试的。

前序遍历和中序遍历的迭代实现让我很困惑。

这里是 leetcode 的问题。

https://leetcode.com/problems/binary-tree-inorder-traversal/

https://leetcode.com/problems/binary-tree-preorder-traversal/

解决方法

我记得它是参考根节点考虑的。

Inorder -> 表示词根是 InBetween Left and Right,

PreOrder -> Root 是 'pre'/before Left and right

Post -> Root 在 Left 和 Right 之后。

,
  1. 先序遍历:

我们沿着图走,从顶部逆时针走。每次我们通过节点的左侧时都大喊。 enter image description here

  1. 中序遍历:

我们沿着图走,从顶部逆时针走。每次越过底部时大喊大叫。 enter image description here

  1. 后序遍历

我们沿着图走,从顶部逆时针走。每次都大喊,当你越过右边时大喊 enter image description here

如果您想查看更多递归和迭代实现细节,请阅读following post

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...