Binary Tree Inorder Traversal 二叉树的中序遍历(迭代非递归版本)
来源:互联网 发布:金山软件有哪些 编辑:程序博客网 时间:2024/05/20 22:39
二叉树的遍历如果用递归的话,是比较好做的。
这里,选择有挑战一点的解法:迭代直接求解。
首先,我们先造一个二叉树。
中序遍历需要先访问完左边的子树,才能访问中间的,最后访问右边子树。
我们自己先模拟中序遍历,4->3->9,9的左子树为空,此时可以输出9了,接着再访问9的右子树。
只有9的右子树访问结束,我们才会去访问前面的3,所以我们需要用一个栈的结构先把前面碰到的节点存储起来。
访问9的右子树的时候,我们可以想象成它就是一个独立的树,所以,6->4,4的左子树为空,可以输出4了。
总结一下:
我们的算法分为3步走:
1. 从当前节点开始,走到最左的节点,中途存储遍历到的节点。
2. 如果这个最左的节点的右子树非空,那么右子树成为当前节点,重复1步骤。
3. 如果这个最左的节点的右子树是空的,那么从栈中弹出更前面的节点。
public List<Integer> inorderTraversal(TreeNode root) { Stack<TreeNode> store = new Stack<>(); List<Integer> list = new ArrayList<>(); if (root == null) { return list; } store.push(root); while (root.left != null) { store.push(root.left); root = root.left; } while (!store.empty()) { TreeNode cur = store.pop(); list.add(cur.val); if (cur.right != null) { root = cur.right;// let cur.right be the current node store.push(root); while (root.left != null) { store.push(root.left); root = root.left; } } } return list; }
1 0
- Binary Tree Inorder Traversal 二叉树的中序遍历(迭代非递归版本)
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- Binary Tree Inorder Traversal 二叉树的中序遍历
- 二叉树的中序遍历 Binary Tree Inorder Traversal
- Binary Tree Inorder Traversal 二叉树的中序遍历
- Binary Tree Inorder Traversal 中序遍历二叉树 递归和非递归版
- Binary Tree Postorder Traversal 二叉树的后序遍历(迭代非递归版本)
- 【leetcode】94Binary Tree Inorder Traversal(非递归中序遍历二叉树)
- LeetCode Binary Tree Inorder Traversal 中序遍历二叉树
- LeetCode | Binary Tree Inorder Traversal(二叉树的中序遍历)
- LeetCode OJ 之 Binary Tree Inorder Traversal (二叉树的中序遍历)
- LeetCode 94. Binary Tree Inorder Traversal(二叉树的中序遍历)
- 67.Binary Tree Inorder Traversal-二叉树的中序遍历(容易题)
- leetcode_94. Binary Tree Inorder Traversal 二叉树的中序遍历,非递归算法,栈的思想
- 94.LeetCode Binary Tree Inorder Traversal(medium)[中序遍历二叉树 树的遍历]
- Binary Tree Preorder Traversal 二叉树的前向遍历(迭代非递归版本)
- LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树、迭代)
- Binary Tree Inorder Traversal——二叉树的中序遍历
- context
- TensorFlow 从入门到精通(八):TensorFlow tf.nn.conv2d 一路追查
- 进程间通信---管道
- 计数排序(代码片段)
- Linux命令积累
- Binary Tree Inorder Traversal 二叉树的中序遍历(迭代非递归版本)
- Failed to load JavaHL Library
- MyEclipse10.6 myeclipse2013下添加jadClipse反编译插件 .
- Linux socket之一:基础函数
- 9-CSS继承,层叠,特殊性
- 斐波那契堆
- 《HTML5移动web开发指南》——笔记3(本地存储)
- poj1321——棋盘问题(DFS)
- 如何让Mysql支持emoji(表情)