先序遍历
从根节点来看,遍历顺序是根 -> 左 -> 右
我们用一个栈来储存二叉树中的节点值,访问一个节点时,先打印这个节点,再将这个节点的左子树和右子树放进栈中,先拿出左子树即可
public static void preOrderUnRecur(Node head) {
System.out.print("pre-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.value + " ");
if (head.right != null) {
stack.push(head.right);
}
if (head.left != null) {
stack.push(head.left);
}
}
}
System.out.println();
}
中序遍历
从根节点来看,遍历顺序是左 -> 根 -> 右
也就是说,我们要先遍历这个二叉树的所有左子树,放进栈中,再遍历右子树
首先先将二叉树所有的左子树放进栈,再依次提出打印,而pop的条件就是当前节点的左子树或右子树为空
public static void inOrderUnRecur(Node head) {
System.out.print("in-order: ");
if (head != null) {
Stack<Node> stack = new Stack<Node>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
后序遍历
从根节点来看,遍历顺序是左 -> 右 -> 根
类似于根 -> 右 -> 左的逆序
public static void posOrderUnRecur1(Node head) {
System.out.print("pos-order: ");
if (head != null) {
Stack<Node> s1 = new Stack<Node>();
Stack<Node> s2 = new Stack<Node>();
s1.push(head);
while (!s1.isEmpty()) {
head = s1.pop();
s2.push(head);
if (head.left != null) {
s1.push(head.left);
}
if (head.right != null) {
s1.push(head.right);
}
}
while (!s2.isEmpty()) {
System.out.print(s2.pop().value + " ");
}
}
System.out.println();
}