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;
}
}
}
}
}
二叉树非递归遍历
最新推荐文章于 2024-11-10 20:17:28 发布