二叉树的前/中/后序遍历算法(非递归)
来源:互联网 发布:魏晨全球歌迷会淘宝网 编辑:程序博客网 时间:2024/06/15 17:55
都由堆栈实现,如下:
先序:
public List<Integer> preorderTraversal(TreeNode root) { Stack<TreeNode> stack=new Stack(); TreeNode rot=root; List<Integer> list=new ArrayList(); while(rot!=null||!stack.empty()) { if(rot!=null) { list.add(rot.val); stack.push(rot); rot=rot.left; } else { rot=stack.pop().right; } } return list;}
中序:
public List<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> stack=new Stack(); List<Integer> list=new ArrayList(); TreeNode rot=root; while(!stack.isEmpty()||rot!=null) { while(rot!=null) { stack.push(rot); rot=rot.left; } TreeNode t1=stack.pop(); list.add(t1.val); rot=t1.right; } return list;}
后序:
public List<Integer> postorderTraversal(TreeNode root) { List<Integer> list=new ArrayList(); Stack<TreeNode> stack=new Stack(); TreeNode current=root; TreeNode previsit=null; while(!stack.isEmpty()||current!=null) { while(current!=null) { stack.push(current); current=current.left; } current=stack.peek(); if(current.right==null||current.right==previsit) { list.add(current.val); stack.pop(); previsit=current; current=null; } else { current=current.right; } } return list;}
0 0
- (前、中、后)序遍历二叉树的递归、非递归算法!
- 【数据结构】二叉树(前、中、后)序遍历的递归与非递归算法
- 二叉树的前/中/后序遍历算法(非递归)
- 二叉树的遍历(前 中 后序 )递归 非递归算法
- 【二叉树遍历算法】——前/中/后序递归与非递归的实现
- 二叉树的非递归【前/中/后 序遍历】
- 二叉树的前序遍历、中序遍历和后序遍历的递归和非递归算法
- 二叉树的前序、中序、后序遍历的算法(递归形式和非递归形式)
- 二叉树的前序、中序、后序的递归与非递归遍历算法实现(待完善)
- 二叉树的遍历(前序,中序,后序,层序)--递归和非递归算法实现
- 二叉树的前序/中序/后序/层序的非递归遍历算法
- 二叉树的非递归前序,中序,后序遍历算法
- 二叉树的遍历: 前序,中序,后序----非递归算法
- 用java实现二叉树非递归的前序,中序,后序遍历算法
- 前序/中序/后序遍历二叉树的非递归算法
- 【二叉树】非递归遍历的通用算法:前序、中序和后序
- 二叉树的创建,遍历(前序,中序,后序)-递归 非递归
- 二叉树的前序、中序、后序(递归、非递归)遍历java实现
- 【java】Synchronize关键字
- Java笔记之三
- 插件maven-compiler-plugin
- Linux多线程——使用信号量同步线程
- ArrayList、Vector、HashMap、HashSet的默认初始容量、加载因子、扩容增量
- 二叉树的前/中/后序遍历算法(非递归)
- 利用SQOOP将数据从数据库导入到HDFS
- swift系列:新手村第一周
- 【HTML】No.5 HTML属性
- 404. Sum of Left Leaves
- Rust: 从csv文件转成kbar的尝试:速度,还有Julia和激情
- servlet 路径
- java(三)
- Mybatis源码拜读