当前位置:网站首页>非递归前中后序遍历二叉树
非递归前中后序遍历二叉树
2022-07-26 22:42:00 【咖啡不加冰和糖】
1 前序遍历
前序遍历为:根、左、右,我们可以借助一个栈来完成遍历,大致思路如下:
- 第一次根节点进栈,然后每次栈顶元素出栈,打印根节点的值value;
- 根节点的右节点进栈;
- 根节点的左结点进栈;
这里是右节点先进栈,然后才是左节点进栈,那么下次出栈的时候就是左节点先出栈,即先遍历根节点的左节点。
参考代码:
public void preOrder(TreeNode root){
if(root == null)return;
LinkedList<TreeNode> stack = new LinkedList<>();
stack.addLast(root);
while(!stack.isEmpty()){
root = stack.removeLast();
System.out.print(root.val + " ");
if(root.right != null)stack.addLast(root.right);//右子结点先进栈
if(root.left != null)stack.addLast(root.left);//左子结点后进栈
}
}
2 中序遍历
前序遍历为:左、根、右,我们也可以借助一个栈来完成遍历,大致思路如下:
- 根结点进栈,左孩子不为空,左孩子进栈,左孩子的左孩子不为空,左孩子的左孩子进栈 …,直到遇到null;
- 遇到null,栈中出栈一个元素,打印value,判断出栈元素有没有右孩子,若有,右孩子进栈,重复第一步的操作,即将它的左孩子进栈。
参考代码:
public void inOrder(TreeNode root){
if(root == null)return;
LinkedList<TreeNode> stack = new LinkedList<>();
while(!stack.isEmpty() || root != null){
if(root != null){
stack.addLast(root);
root = root.left; //每次将左孩子进栈
}
else{
root = stack.removeLast();
System.out.print(root.val + " ");
root = root.right;//下次循环,右孩子进栈
}
}
}
3 后序遍历
后序遍历顺序为:左、右、根。这里要借助2个栈来完成。大致思路如下:
- 第一次将根节点入栈1,后面每次栈顶元素出栈并进入栈2;
- 根节点的左孩子不为空,左孩子进栈1;
- 根节点的右孩子不为空,右孩子进栈1;
- 重复上述操作(此时根节点不用进栈)
这样的话,栈2元素的顺序从栈底到栈顶为:根、右、左。那么栈2进行一次出栈后,出栈顺序为左、右、根。
public void postOrder(TreeNode root){
if(root== null)return;
LinkedList<TreeNode> stack1 = new LinkedList<>();
LinkedList<TreeNode> stack2 = new LinkedList<>();
stack1.addLast(root);
while(!stack1.isEmpty()){
root = stack1.removeLast();
if(root.left != null)stack1.addLast(root.left);
if(root.right != null)stack1.addLast(root.right);
stack2.addLast(root);
}
while(!stack2.isEmpty()){
TreeNode node = stack2.removeLast();
System.out.print(node.val + " ");
}
}
测试:
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
TreeNode left = new TreeNode(2);
TreeNode right = new TreeNode(3);
root.left = left;
root.right = right;
System.out.println("前序遍历结果:");
preOrder(root);
System.out.println();
System.out.println("中序遍历结果:");
inOrder(root);
System.out.println();
System.out.println("后序遍历结果:");
postOrder(root)
}

(完)
边栏推荐
- Flink 1.15 implements SQL script to recover data from savepointh
- Real time calculation demo based on Flink: user behavior analysis (IV: how many different users have visited the website (UV) in a period of time)
- 短视频App开发有哪些必备的功能?
- C # conversion of basic data types for entry
- Game project export AAB package upload Google tips more than 150m solution
- Tencent upgrades the live broadcast function of video Number applet. Tencent's foundation for continuous promotion of live broadcast is this technology called visual cube (mlvb)
- MySQL uses and implements ranking functions rank and deny_ Rank and row_ NUMBER
- Flink1.11 intervalJoin watermark生成,状态清理机制源码理解&Demo分析
- Cannot find a valid baseurl for repo: HDP-3.1-repo-1
- flink需求之—SideOutPut(侧输出流的应用:将温度大于30℃的输出到主流,低于30℃的输出到侧流)
猜你喜欢

flink需求之—ProcessFunction(需求:如果30秒内温度连续上升就报警)

Understanding of Flink checkpoint source code

redis——缓存雪崩、缓存穿透、缓存击穿

(Spark调优~)算子的合理选择

解决Pytorch中Cuda无法GPU加速问题

Game project export AAB package upload Google tips more than 150m solution

More than live streaming: what other eye-catching functions does Tencent cloud live mlvb plug-in have besides streaming / streaming

The difference between golang slice make and new

不止直播:腾讯云直播MLVB 插件除了推流/拉流还有哪些亮眼功能

flink需求之—SideOutPut(侧输出流的应用:将温度大于30℃的输出到主流,低于30℃的输出到侧流)
随机推荐
Hidden index and descending index in MySQL 8.0 (new feature)
Solve the problem of direct blue screen restart when VMware Workstation virtual machine starts
Which securities company has a low stock commission and which stock is safe to open an account
Flink based real-time project: user behavior analysis (II: real-time traffic statistics)
Isolation level of MySQL database transactions (detailed explanation)
Flink1.11 intervaljoin watermark generation, state cleaning mechanism source code understanding & demo analysis
Flink's fault tolerance mechanism (checkpoint)
腾讯云MLVB技术如何在移动直播服务中突出重围之基础概念
哪个证券公司开户股票佣金低,哪个股票开户安全
智密-腾讯云直播 MLVB 插件优化教程:六步提升拉流速度+降低直播延迟
视频类小程序变现的最短路径:从带货到品牌营销
Spark on yarn's job submission process
Spark On YARN的作业提交流程
In 2022, will there be opportunities for mobile Internet apps and short video live tracks?
Flink based real-time project: user behavior analysis (I: real-time popular product statistics)
使用tika 判断文件类型
Flink的容错机制(checkpoint)
MYSQL数据库事务的隔离级别(详解)
Simple explanation of database table connection
Use Tika to judge the file type