当前位置:网站首页>二叉树的前中后序遍历——本质(每个节点都是“根”节点)
二叉树的前中后序遍历——本质(每个节点都是“根”节点)
2022-07-26 05:54:00 【学习追求高效率】
重点是自己要做一下题
在二叉树的遍历的三种方法中
根-左-右
左-根-右
左-右-根
记住每个节点都是根
所以前序遍历的时候,会先“忽略”右子树
中序遍历的时候,不会先打印 上一个根的左子树(因为可能上一个根的左子树,也是其它节点的根)
后续遍历的时候,把每个根遍历完,才能打印出根节点
注意:每次遍历到的节点,其实都是根节点
1.前序遍历(每次遍历的节点都先当做根)
2. 中序遍历(只有把根的左子树遍历完,再打印根)
3. 后序遍历(只有把左右子树都遍历完,再打印根)
- NLR:前序遍历(Preorder Traversal 亦称先序遍历)——访问根结点—>根的左子树—>根的右子树。
- LNR:中序遍历(Inorder Traversal)——根的左子树—>根节点—>根的右子树。
- LRN:后序遍历(Postorder Traversal)——根的左子树—>根的右子树—>根节点
前序遍历结果:1 2 3 4 5 6(每次遍历的节点都先当做根)
中序遍历结果:3 2 1 5 4 6(只有把根的左子树遍历完,再打印根)
后序遍历结果:3 1 5 6 4 1(只有把左右子树都遍历完,再打印根)
// 前序遍历
void preOrder(TreeNode root) {
if(root == null) return;
System.out.print(root.val+" ");
preOrder(root.left);
preOrder(root.right);
}
// 中序遍历
void inOrder(TreeNode root) {
if(root == null) return;
inOrder(root.left);
System.out.print(root.val+" ");
inOrder(root.right);
}
// 后序遍历
void postOrder(TreeNode root) {
if(root == null) return;
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val+" ");
}
边栏推荐
- 满二叉树 / 真二叉树 / 完全二叉树 ~
- The refurbishment and counterfeiting of chips have made people feel numb
- Mysql45 talking about logging system: how does an SQL UPDATE statement execute?
- 某公司给每个工位装监控:只为看员工写代码?
- Introduction to Chinese text error correction task
- 卸载手机自带APP的操作步骤
- Unity2D 动画器无法 创建过渡
- [MySQL must know and know] time function number function string function condition judgment
- idea yml 文件代码不提示解决方案
- 金仓数据库 KingbaseES SQL 语言参考手册 (10. 查询和子查询)
猜你喜欢

Motor control column summary

Lemon class automatic learning after all

CANoe-XML在Test Modules中的应用

ES Cluster in Red status: what about write & delete operations?

Application and value of IVR in VoIP telephone system

Mysql45 speak in simple terms index

1.12 Web开发基础

卸载手机自带APP的操作步骤

DOM operation -- operation node

SSH Remote Management
随机推荐
Lamp architecture
Mysql45 talking about global lock, table lock and row lock
Should we test the Dao layer?
Two auxiliary functions of integral Mall for business user operation
Talking about the practice of software defect management
How to name the project version number? Looks like cow b
unity 像素画导入模糊问题
Who is responsible for the problems of virtual idol endorsement products? And listen to the lawyer's analysis
Another open source artifact, worth collecting and learning!
Ros2 knowledge: DDS basic knowledge
某公司给每个工位装监控:只为看员工写代码?
Redis持久化-RDB
对接微信支付(二)统一下单API
程序员如何改善精神内耗?
Autumn move - Preparation Plan
为什么LPDDR不能完全代替DDR?
Jupiter notebook shortcut key
满二叉树 / 真二叉树 / 完全二叉树 ~
Solution to slow download speed of vagrant
I also found excellent software and hardware projects, all open source
