二叉樹前中後遍歷非遞歸版本
先序遍歷:
首先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();
}
這跟先序遍歷很相似,先序遍歷彈出一個元素就打印,而後序遍歷使得一個棧彈出棧頂時不打印元素,保存在另一個棧中,先序遍歷是右孩子先進然後左孩子進,而後序遍歷是左孩子進然後右孩子進。