二叉树的前序、中序、后序遍历
二叉树的前序、中序、后序 递归和非递归方式进行遍历
后序非递归方式遍历比较复杂,在栈中回退时,需要判断是从左结点回还是右结点回,如果从左结点,将右结点标记,进行处理,如果从右结点返回,则应该弹出栈
import java.util.Stack; class TreeNode{ int value; TreeNode left; TreeNode right; TreeNode(int value){ this.value=value; } public class Tree { public static void main(String[] args) { TreeNode[] nodes=new TreeNode[10]; for(int i =0;i < 10; i ++){ nodes[i] = new TreeNode(i); } for(int i =0;i<10;i ++){ if(i*2+1<10){ nodes[i].left=nodes[2*i+1]; } if(i*2+2<10){ nodes[i].right=nodes[2*i+2]; } } preOrder(nodes[0]); System.out.println(); preOrder2(nodes[0]); System.out.println(); midOrder(nodes[0]); System.out.println(); midOrder2(nodes[0]); System.out.println(); postOrder(nodes[0]); System.out.println(); postOrder2(nodes[0]); } /* 前序遍历的递归实现 */ public static void preOrder(TreeNode node){ System.out.print(node.value); System.out.print(" "); if(node.left!= null){ preOrder(node.left); } if(node.right != null){ preOrder(node.right); } } /* 前序遍历的非递归实现 */ public static void preOrder2(TreeNode node){ Stack<TreeNode> stack= new Stack<TreeNode>(); while (node != null || !stack.isEmpty()){ while (node != null){ System.out.print(node.value); System.out.print(" "); stack.push(node); node = node.left; } if(!stack.isEmpty()){ TreeNode tem=stack.pop(); node=tem.right; } } } /* 中序遍历的递归实现 */ public static void midOrder(TreeNode node){ if(node.left != null){ midOrder(node.left); } System.out.print(node.value); System.out.print(" "); if(node.right != null){ midOrder(node.right); } } /* 中序遍历的非递归实现 */ public static void midOrder2(TreeNode node){ Stack<TreeNode> stack=new Stack<TreeNode>(); while (node !=null || !stack.isEmpty()){ while (node!=null){ stack.push(node); node=node.left; } if(!stack.isEmpty()){ TreeNode tem=stack.pop(); System.out.print(tem.value); System.out.print(" "); node=tem.right; } } } /* 后序遍历的递归实现 */ public static void postOrder(TreeNode node){ if(node.left != null){ postOrder(node.left); } if(node.right != null){ postOrder(node.right); } System.out.print(node.value); System.out.print(" "); } /* 后序遍历的非递归实现 */ public static void postOrder2(TreeNode node){ int left=1,right=2; Stack<TreeNode> stack=new Stack<TreeNode>();
//辅助栈 用来标记现在栈的结点是右子树还是左 Stack<Integer> stack2=new Stack<Integer>(); while (node != null || !stack.isEmpty()){ while (node!=null){ stack.push(node); stack2.push(left); node=node.left; } while (!stack.isEmpty() &&stack2.peek() == right ){ stack2.pop(); TreeNode temp = stack.pop(); System.out.print(temp.value); System.out.print(" "); } if(!stack.isEmpty() && stack2.peek() == left){ stack2.pop(); stack2.push(right); node=stack.peek().right; } } } }