非递归遍历二叉树
2018-02-28 17:30
246 查看
非递归前序遍历
1.申请栈,将头节点压入栈2.从栈中弹出顶节点,保存值,若右子树不为空,压入右孩子.若左孩子不为空,压入左孩子
3.重复2.直到栈为空public ArrayList<Integer> preOrderUnRecur(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
LinkedList<TreeNode> stack = new LinkedList<>();
if (root == null) {
return res;
}
stack.push(root);
while (stack.isEmpty() == false) {
TreeNode cur = stack.pop();
res.add(cur.val);
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
return res;
}
非递归中序遍历
1.申请栈,将头节点压入栈 , 记作cur节点2.依次把节点左边界压入栈, cur = cur.left 然后重复 2
3.重复2.直到 cur 为空. 此时从栈中弹出一个节点.记为node 保存值. 然 cur = node.right 重复2.public ArrayList<Integer> inOrderUnRecur(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root != null) {
LinkedList<TreeNode> stack = new LinkedList<>();
while (stack.isEmpty() == false || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
TreeNode cur = stack.pop();
res.add(cur.val);
root = cur.right;
}
}
}
return res;
}
非递归后序遍历
1.申请栈 s1,和s2,将头节点压入s12.从s1 弹出节点 cur 把cur 左孩子,右孩子 依次压入s1
3.s1 每弹出一个节点,便压入 s2
4.重复 2, 3. 直到 s1 为空
5.从s2 中 依次弹出节点保存
s1 弹出顺序 为 中 右 左
s2 就是将s1 逆序 弹出顺序 左 右 中 即为后序遍历public ArrayList<Integer> postOrderUnRecur(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
if (root != null) {
LinkedList<TreeNode> stack1 = new LinkedList<>();
LinkedList<TreeNode> stack2 = new LinkedList<>();
stack1.push(root);
while (stack1.isEmpty() == false) {
root = stack1.pop();
stack2.push(root);
if (root.left != null) {
stack1.push(root.left);
}
if (root.right != null) {
stack1.push(root.right);
}
}
while (stack2.isEmpty() == false) {
res.add(stack2.pop().val);
}
}
return res;
}
相关文章推荐
- 二叉树的三种遍历非递归实现
- 二叉树操作(插入、删除、遍历(递归与非递归))
- 二叉树建立,递归,非递归,前序,中序,后序遍历
- 非递归遍历二叉树
- 二叉树非递归遍历
- 二叉树的递归遍历
- 二叉树按层次遍历的递归用法
- 二叉树的三种遍历的非递归实现
- 二叉树前序遍历的递归与非递归算法
- 二叉树的层序遍历(递归和非递归)
- 二叉树的创建(先序创建的)及先序遍历 中序遍历 后序遍历的递归和非递归实现
- 二叉树的遍历(递归遍历)
- 二叉树创建以及遍历(递归和非递归方式)
- 非递归遍历二叉树
- 二叉树的非递归遍历及其递归遍历
- 二叉树的遍历:前序,中序,后序,层序--包括递归和非递归实现
- 二叉树的递归遍历
- 二叉树:创建,遍历(递归、非递归、层次)
- 【数据结构】二叉树前中后序遍历、层序遍历(递归实现)
- [数据结构]后序非递归遍历二叉树