二叉树前中后遍历非递归版本
先序遍历:
首先1进栈
判断栈不为空,1出栈,并且右孩子先进栈,然后左孩子进栈
栈顶元素2出栈,并且2的右孩子5和左孩子4依次进栈
然后4出栈,4没有左右孩子,所以不存在进栈元素
5出栈
3出栈,3的右孩子7和左孩子6进栈
6出栈
7出栈
栈为空结束
出栈顺序: 1 2 4 5 3 6 7
//先序遍历
public static void preOrderUnRecur(Node head) {
System.out.print("pre-order: ");
if(head != null) {
Stack<Node> stack = new Stack<Node>();
stack.push(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();
}
中序遍历:将根节点的左孩子进栈,只要左孩子的左孩子节点不为空,就依次入栈
当最后左孩子节点为空时,从栈顶弹出元素,节点指向弹出元素的右孩子。
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();
}
这跟先序遍历很相似,先序遍历弹出一个元素就打印,而后序遍历使得一个栈弹出栈顶时不打印元素,保存在另一个栈中,先序遍历是右孩子先进然后左孩子进,而后序遍历是左孩子进然后右孩子进。