您的位置:首页 > 其它

非递归遍历二叉树

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,将头节点压入s1

2.从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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: