前序遍历:
借助一个栈实现前序遍历。如果根节点非空,将根节点入栈。如果栈不为空, 循环遍历取栈顶元素,然后将该元素的右结点入栈,再将将该元素的左结点入栈(因为栈是后进先出)。直至栈为空,遍历结束。
中序遍历:
让cur从root出发,循环往左找,如果root!=null,将该结点入栈,直到root==null,遍历结束。取出栈顶元素top,打印栈顶元素,并将cur从当前栈顶元素的右子树出发,循环刚才的过程。
后序遍历:
让cur从root出发,循环往左找,如果cur!=null,将路径上的所有结点都入栈。取出栈顶元素(此时不一定访问,如果栈顶元素右子树为空或者右子书一定被访问过了,才能打印该栈顶元素)。
代码如下:
class TreeNode {
public char val;
TreeNode left;
TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
public class BinaryTreeLoop {
//构建一颗树
public static TreeNode build(){
TreeNode A=new TreeNode('A');
TreeNode B=new TreeNode('B');
TreeNode C=new TreeNode('C');
TreeNode D=new TreeNode('D');
TreeNode E=new TreeNode('E');
TreeNode F=new TreeNode('F');
TreeNode G=new TreeNode('G');
TreeNode H=new TreeNode('H');
A.left=B;
A.right=C;
B.left=D;
B.right=E;
E.left=G;
G.right=H;
C.right=F;
return A;
}
//前序遍历,非递归
public static void preOrderByLoop(TreeNode root){
if(root==null){
return;
}
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur=stack.pop();
System.out.print(cur.val+" ");
if(cur.right!=null){
stack.push(cur.right);
}
if(cur.left!=null){
stack.push(cur.left);
}
}
}
//中序遍历,非递归
public static void inOrderByLoop(TreeNode root){
if(root==null){
return;
}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(true){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
if(stack.isEmpty()){
break;
}
TreeNode top=stack.pop();
System.out.print(top.val+" ");
cur=top.right;
}
}
//后序遍历,非递归访问
public static void postOrderByLoop(TreeNode root){
if(root==null){
return;
}
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
TreeNode prev=null;
while(true){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
if(stack.isEmpty()){
break;
}
TreeNode top=stack.peek();
if(top.right==null||prev==top.right){
System.out.print(top.val+" ");
stack.pop();
//prev用来标记后序遍历过程中最后一个被访问的元素。
prev=top;
}
else{
cur=top.right;
}
}
}
public static void main(String[] args) {
TreeNode root=build();
System.out.println("前序遍历:");
preOrderByLoop(root);
System.out.println();
System.out.println("中序遍历:");
inOrderByLoop(root);
System.out.println();
System.out.println("后序遍历:");
postOrderByLoop(root);
System.out.println();
}
}