import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Traverse {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
Node n6 = new Node(6);
Node n7 = new Node(7);
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
n3.left = n6;
n3.right = n7;
preOrder(n1);
inOrder(n1);
postOrder(n1);
levelOrder(n1);
}
static void preOrder(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
Node cur = stack.pop();
System.out.print(cur.value + " ");
// 因为先序遍历是“根左右”,先左后右,所以入栈的时候要先右后左的入,出栈时才能先左后有
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
System.out.println();
}
static void inOrder(Node head) {
if (head == null) {
return;
}
Stack<Node> stack = new Stack<>();
Node cur = head;
// 当cur不为空时,可能是左边节点要继续进栈;也可能是右边节点要进栈;所以还要继续处理,这时不能结束循环。
// 当栈不空时,肯定还没处理完所有元素,这时也不能结束循环
while (!stack.isEmpty() || cur != null) {
if (cur != null) {
stack.push(cur);
// 一直向左找,找到最左边的节点
cur = cur.left;
} else {
cur = stack.pop();
System.out.print(cur.value + " ");
// 弹栈的时候,说明该节点已经遍历完成,这时该遍历右子树了,所以现在要处理右子树的根节点。若不为空,则会进栈,若为空,则可能继续弹栈或结束循环。
cur = cur.right;
}
}
System.out.println();
}
static void postOrder(Node head) {
if (head == null) {
return;
}
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(head);
while (!s1.isEmpty()) {
Node cur = s1.pop();
s2.push(cur);
if (cur.left != null) {
s1.push(cur.left);
}
if (cur.right != null) {
s1.push(cur.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
System.out.println();
}
static void levelOrder(Node head) {
if (head == null) {
return;
}
Queue<Node> queue = new LinkedList<>();
// 根节点先入队
queue.offer(head);
// 当队列不空时,将队头元素出队的同时存入临时变量,并输出该节点的值
while (queue.peek() != null) {
Node temp = queue.poll();
System.out.print(temp.value + " ");
// 左节点先入队
if (temp.left != null) {
queue.offer(temp.left);
}
// 右节点后入队
if (temp.right != null) {
queue.offer(temp.right);
}
}
System.out.println();
}
}
class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
}
}
二叉树的三种非递归遍历及层序遍历
最新推荐文章于 2022-10-03 20:19:04 发布