树的前序、中序、后序非递归遍历总结
来源:互联网 发布:淘宝法院拍卖网 编辑:程序博客网 时间:2024/06/01 09:00
参考自:这里
- 前序遍历
/* * 当一个指针从栈中弹出来时,此树的左子树已经遍历完成。 * p如果不为空,表示当前需要遍历p所指向的树(这棵树还没有开始遍历)。 */public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.add(p.val); // Add before going to children p = p.left; } else { TreeNode node = stack.pop(); p = node.right; } } return result;}
- 中序遍历
/* * 当一个指针从栈中弹出来时,此树的左子树已经遍历完成。 * p如果不为空,表示当前需要遍历p所指向的树(这棵树还没有开始遍历)。 */public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); p = p.left; } else { TreeNode node = stack.pop(); result.add(node.val); // Add after all left children p = node.right; } } return result;}
- 后序遍历
/* * 后序遍历的反向结果是类似与先序遍历的形式:根->右子树->左子树 * 当一个指针从栈中弹出来时,此树的右子树已经遍历完成。 * p如果不为空,表示当前需要遍历p所指向的树(这棵树还没有开始遍历)。 */public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> result = new LinkedList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode p = root; while(!stack.isEmpty() || p != null) { if(p != null) { stack.push(p); result.addFirst(p.val); // Reverse the process of preorder p = p.right; // Reverse the process of preorder } else { TreeNode node = stack.pop(); p = node.left; // Reverse the process of preorder } } return result;}
1 0
- 树的前序、中序、后序非递归遍历总结
- 前序和中序重建二叉树, 树的前序递归,中序递归,后序递归遍历和前序非递归,中序非递归,后序非递归遍历
- 二叉树的前序、中序、后序非递归遍历
- 二叉树的中序,前序,后序非递归遍历
- 树的创建、前、中、后序递归遍历
- 二叉树的非递归【前/中/后 序遍历】
- 【二叉树】 前序、中序和后序的递归遍历与非递归遍历
- 树的前序遍历非递归、中序遍历非递归、后序遍历非递归
- leetcode | 二叉树的前序遍历、中序遍历、后续遍历的非递归实现
- 非递归实现二叉树的后序遍历、前序遍历、中序遍历
- 树的非递归前序遍历
- 树的前/中/层序遍历(前/中递归实现,层序队列实现)
- 二叉树的前序遍历、中序遍历和后序遍历的递归和非递归算法
- 二叉树的前序遍历、中序遍历、后续遍历 (包括递归、非递归,共六种)
- 前序遍历 中序遍历 后续遍历的递归与非递归算法
- 二叉树--实现二叉树的前序/中序/后序非递归遍历。
- 实现二叉树的前序/中序/后序非递归遍历——题集(十一)
- 每日一题之实现二叉树的前序/中序/后序非递归遍历
- Mysql数据库mysql-5.7.18-winx64安装笔记
- 用echarts做最近15天学习时间的统计
- Java,Android定时任务的写法
- mysql基本操作
- IP address '121.41.35.30' could not be resolved: Name or service not known解决方法
- 树的前序、中序、后序非递归遍历总结
- Karaoke 歌曲播放
- linux network namespace 例子
- MongoDB修改器($inc/$set/$unset/$push/$pop/upsert)
- FastReport中如何加入自定义函数
- mustache语法
- Android内存优化的关键点
- 复杂链表复制
- SFTP使用JSCH库链接不断开解决方法