1 package test; 2 3 import org.junit.Test; 4 5 /** 6 * 二叉树的遍历 7 * @author Fzz 8 * @date 2018年1月17日 9 * @Description TODO: 10 */ 11 public class BinaryTreeTraversal { 12 private StringBuffer sb = new StringBuffer(); 13 //先序遍历(数组) 14 public String first(Object[] o,int i){ 15 //访问根结点 16 sb.append(o[i]); 17 //遍历左子树 18 int left = i*2; 19 if(left<o.length&&o[left]!=null) 20 first(o,left); 21 //遍历右子树 22 int right = i*2+1; 23 if(right<o.length&&o[right]!=null) 24 first(o,right); 25 return sb.toString(); 26 } 27 28 //中序遍历 29 public String mid(Object[] o,int i){ 30 //遍历左子树 31 int left = i*2; 32 if(left<o.length&&o[left]!=null) 33 mid(o,left); 34 //访问根结点 35 sb.append(o[i]); 36 //遍历右子树 37 int right = i*2+1; 38 if(right<o.length&&o[right]!=null) 39 mid(o,right); 40 return sb.toString(); 41 } 42 43 //后序遍历 44 public String last(Object[] o,int i){ 45 //遍历左子树 46 int left = i*2; 47 if(left<o.length&&o[left]!=null) 48 last(o,left); 49 //遍历右子树 50 int right = i*2+1; 51 if(right<o.length&&o[right]!=null) 52 last(o,right); 53 //访问根结点 54 sb.append(o[i]); 55 return sb.toString(); 56 } 57 58 //将缓存区设为空 59 public void setBufferNull(){ 60 this.sb = this.sb.delete(0, sb.length()); 61 } 62 63 @Test 64 public void test(){ 65 Character[] o = {null,'A','B','C','D',null,'E','F'}; 66 //遍历前先清空缓存区 67 this.setBufferNull(); 68 String s = first(o,1); 69 System.out.println("先序遍历结果:"+s); 70 this.setBufferNull(); 71 s = mid(o,1); 72 System.out.println("中序遍历结果:"+s); 73 this.setBufferNull(); 74 s = last(o,1); 75 System.out.println("后序遍历结果:"+s); 76 } 77 }
数据结构之二叉树(BinaryTree) (15)
内容版权声明:除非注明,否则皆为本站原创文章。