public class BiTreeTraversal {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
//先序遍历
void preOrder(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
//先遍历后入栈
while (root != null) {
System.out.print(root.val + " ");
stack.push(root);
root = root.left;
}
//根和左孩子都遍历完了,则更新root为当前节点的右孩子
if (!stack.isEmpty()) {
TreeNode t = stack.pop();
root = t.right;
}
}
}
//中序遍历
void inOrder(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
//先把左孩子全部入栈
while (root != null) {
stack.push(root);
root = root.left;
}
//出栈后就可遍历
if (!stack.isEmpty()) {
TreeNode t = stack.pop();
System.out.print(t.val + " ");
root = t.right;
}
}
}
//后序遍历
void postOrder(TreeNode root) {
if (root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode last = null;
while (!stack.isEmpty() || root != null) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (!stack.isEmpty()) {
TreeNode t = stack.pop();
//当前节点的右孩子为空,或右孩子已访问过
if (t.right == null || last == t.right) {
System.out.print(t.val + " ");
last = t;
} else {
//因为当前结点未打印,所以要重新放回去,等右孩子打印完之后回来打印
stack.push(t);
root = t.right;
}
}
}
}
}
二叉树非递归遍历
最新推荐文章于 2025-12-22 10:04:35 发布
本文详细介绍了二叉树的三种遍历算法:先序遍历、中序遍历和后序遍历,通过使用栈来实现非递归方式的遍历过程,帮助读者深入理解二叉树的数据结构及其操作。
1499

被折叠的 条评论
为什么被折叠?



