//下面代码会用到的树结构
/*
1
2 3
4 5 7
6
先序遍历: 1 2 4 6 5 3 7
中序遍历: 6 4 2 5 1 3 7
后序遍历: 6 4 5 2 7 3 1
*/
先序遍历
遍历思想:自己准备一个栈,先把头结点压入栈中,如果栈不等于空,那就进行循环,每次先弹出一个节点,打印出来,然后再判断右子树是否为空,不为空压入栈中,再判断左子树是否为空,不为空压入栈中。
//先序遍历:头左右
public static void preOrderUnRecur(TreeNode head){
System.out.print("preorder:");
if (head == null){
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.add(head);
while (!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.print(" "+node.val);
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
}
中序遍历
遍历思想:准备一个栈。如果结点不为空,把结点压入栈中,结点向左移动,如果结点为空,那么弹出结点,结点向右移动,循环
//中序遍历 左头右
public static void inOrderUnRecur(TreeNode head){
System.out.print("inorder: ");
if (head!=null){
Stack<TreeNode> stack = new Stack<>();
while(!stack.isEmpty() || head != null){
if (head != null){
stack.push(head);
head = head.left;
}else {
head = stack.pop();
System.out.print(head.val+" ");
head = head.right;
}
}
}
}
后序遍历
遍历思想:准备两个栈,第一个的压栈顺序为先压左再右,每次弹出一个压入辅助栈中,最后弹出辅助栈中的节点。
1 2 3 4 5 7 6
每趟栈中的值
第一趟 s1 : 1 s2 :
第二趟 s1 : 2 3 s2 :1
第三趟 s1 : 2 7 s2 :1 3
第四趟 s1 : 2 s2 :1 3 7
第五趟 s1 : 4 5 s2 :1 3 7 2
第六趟 s1 : 4 s2 :1 3 7 2 5
第七趟 s1 : 6 s2 :1 3 7 2 5 4
第八趟 s1 : s2 :1 3 7 2 5 4 6
把s2弹空,后序遍历的顺序为 6 4 5 2 7 3 1
//后序遍历 左右头
public static void posOrderUnRecur(TreeNode head){
System.out.print("posOrder: ");
if (head != null){
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>(); //辅助栈, 压入顺序为头 右 左
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()){
head = s2.pop();
System.out.print(head.val+" ");
}
}
}