【注】后续实现第二种方法暂时未解出
1 package com.exe4.offer; 2 3 import java.util.Stack; 4 5 /** 6 * 前序、中序、后序遍历方法 7 * @author WGS 8 * 9 */ 10 public class BianliOfBinarryTree { 11 public static class TreeNode { 12 int val = 0; 13 TreeNode left = null; 14 TreeNode right = null; 15 16 public TreeNode(int val) { 17 this.val = val; 18 19 } 20 } 21 /** 22 * 方法一:大话数据结构中简便方法,可实现操作。 23 * @param args 24 */ 25 26 public void preOrder(TreeNode node){ 27 if(node==null) return; 28 System.out.print(node.val+" "); 29 preOrder(node.left); 30 preOrder(node.right); 31 } 32 public void inOrder(TreeNode node){ 33 if(node==null) return; 34 inOrder(node.left); 35 System.out.print(node.val+" "); 36 inOrder(node.right); 37 } 38 public void postOrder(TreeNode node){ 39 if(node==null) return; 40 postOrder(node.left); 41 postOrder(node.right); 42 System.out.print(node.val+" "); 43 } 44 /** 45 * 方法二:剑指offer中的方法:加入栈操作 46 * @param args 47 */ 48 public void preOrder2(TreeNode node){ 49 Stack<TreeNode> stack=new Stack<TreeNode>(); 50 51 while(node!=null || !stack.empty()){ 52 //先遍历左子树 53 while(node!=null){ 54 System.out.print(node.val+" "); 55 stack.push(node); 56 node=node.left;//左子树遍历结束后,node==null,跳出此循环 57 } 58 //左子树遍历结束,继续遍历右子树 59 if(!stack.isEmpty()){ 60 node=stack.pop();//一直返回,直到根节点处,node==null,即stack==isEmpty() 61 node=node.right; 62 } 63 } 64 } 65 public void inOrder2(TreeNode node){ 66 Stack<TreeNode> stack=new Stack<TreeNode>(); 67 while(node!=null || !stack.isEmpty()){ 68 69 while(node!=null){ 70 stack.push(node);//8 6 5 71 node=node.left; //6 5 null 72 } 73 74 if(!stack.isEmpty()){ 75 node=stack.pop();//5 6 76 System.out.print(node.val+" ");//5 6 77 node=node.right;//null 78 } 79 } 80 } 81 //后序遍历暂时还不会 82 /*public void postOrder2(TreeNode node){ 83 Stack<TreeNode> stack=new Stack<TreeNode>(); 84 while(node!=null || !stack.isEmpty()){ 85 while(node!=null){ 86 stack.push(node);//8 6 5 7 87 node=node.left;//6 5 null null 88 } 89 if(!stack.isEmpty()){ 90 node=stack.pop();//5 6 7 91 node=node.right;//null 7 null 92 93 } 94 95 } 96 }*/ 97 98 public static void main(String[] args) { 99 TreeNode root = new TreeNode(8); 100 TreeNode node1 = new TreeNode(6); 101 TreeNode node2 = new TreeNode(10); 102 TreeNode node3 = new TreeNode(5); 103 TreeNode node4 = new TreeNode(7); 104 TreeNode node5 = new TreeNode(9); 105 TreeNode node6 = new TreeNode(11); 106 107 root.left = node1; 108 root.right = node2; 109 node1.left = node3; 110 node1.right = node4; 111 node2.left = node5; 112 node2.right = node6; 113 114 BianliOfBinarryTree bianli=new BianliOfBinarryTree(); 115 bianli.preOrder(root); 116 System.out.println("《《前序遍历-------"); 117 bianli.inOrder(root); 118 System.out.println("《《中序遍历-------"); 119 bianli.postOrder(root); 120 System.out.println("《《后序遍历-------"); 121 bianli.preOrder2(root); 122 System.out.println("方法二:《《前序遍历-------"); 123 bianli.inOrder2(root); 124 System.out.println("方法二:《《中序遍历-------"); 125 // bianli.postOrder2(root); 126 System.out.println("方法二:《《后序遍历-------"); 127 } 128 129 }