java二叉树的简单实现,可以简单实现深度为n的二叉树的建立,二叉树的前序遍历,中序遍历,后序遍历输出。
1 /** 2 *数据结构之树的实现 3 *2016/4/29 4 * 5 **/ 6 package cn.Link; 7 8 public class Tree { 9 Node head = new Node(); 10 Tree(){} 11 12 //内部节点类 13 class Node{ 14 String date; 15 Node left; 16 Node right; 17 Node(){ } 18 Node(String date){ 19 this.date = date; 20 this.left = null; 21 this.right = null; 22 } 23 } 24 25 //给深度为n的满二叉树添加数据 n表示数的深度 26 public void addTree(Node preNode,int n){ 27 if(n ==1) return; 28 preNode.date = "sum"+n; 29 Node preNodeLeft = new Node(); 30 Node preNodeRight = new Node(); 31 32 preNode.left = preNodeLeft; 33 addTree(preNodeLeft,n-1); 34 preNode.right = preNodeRight; 35 addTree(preNodeRight,n-1); 36 } 37 38 //前序遍历二叉树 并输出 39 public void printTreePre(Node preNode){ 40 if(preNode == null) return; 41 if(preNode.left!=null || preNode.right!=null) 42 System.out.print(preNode.date+" "); 43 44 printTreePre(preNode.left); 45 printTreePre(preNode.right); 46 } 47 48 //中序遍历二叉树 并输出 49 public void printTreeAmong(Node preNode){ 50 if(preNode == null) return; 51 printTreeAmong(preNode.left); 52 if(preNode.left!=null || preNode.right!=null) 53 System.out.print(preNode.date+" "); 54 printTreeAmong(preNode.right); 55 } 56 57 //后序遍历二叉树 并输出 58 public void printTreeRear(Node preNode){ 59 if(preNode == null) return; 60 printTreeRear(preNode.left); 61 printTreeRear(preNode.right); 62 63 if(preNode.left!=null || preNode.right!=null) 64 System.out.print(preNode.date+" "); 65 } 66 67 68 //测试函数 69 public static void main(String [] args){ 70 Tree tree = new Tree(); 71 tree.addTree(tree.head,4); 72 System.out.println("================前序遍历================"); 73 tree.printTreePre(tree.head); 74 System.out.println(); 75 System.out.println("================中序遍历==============="); 76 tree.printTreeAmong(tree.head); 77 System.out.println(); 78 System.out.println("================后序遍历==============="); 79 tree.printTreeRear(tree.head); 80 System.out.println(); 81 System.out.println("============手工输出所有数据==========="); 82 System.out.println(tree.head.date); 83 System.out.println(tree.head.left.date+" "+tree.head.right.date); 84 System.out.println(tree.head.left.left.date+" "+tree.head.left.right.date+" "+tree.head.right.left.date+" "+tree.head.right.right.date); 85 } 86 }