java版二叉树算法实现
2016-03-17 21:51 taixuyingcai 阅读(234) 评论(0) 编辑 收藏 举报1 import java.util.ArrayList; 2 class BinaryTree { 3 private static class TreeNode { 4 int data; 5 TreeNode left; 6 TreeNode right; 7 TreeNode(int data){ 8 this.data = data; 9 left = null; 10 right = null; 11 } 12 } 13 14 static int[] arr = {1,2,3,4,5,6,7,8,9}; 15 static ArrayList<TreeNode> tree = new ArrayList<TreeNode>(); 16 private static void creatTree() { 17 for(int i = 0; i < arr.length; i++) { 18 tree.add(new TreeNode(arr[i])); 19 } 20 21 // 建立父亲与孩子关系 22 for(int i = 0; i <= arr.length / 2 - 1; i++) { 23 tree.get(i).left = tree.get(i * 2 + 1); 24 tree.get(i).right = tree.get(i * 2 + 2); 25 } 26 // int lastParent = arr.length / 2 - 1; 27 // tree.get(lastParent).left = tree.get(lastParent * 2 + 1); 28 // if(arr.length % 2 == 1) { 29 // tree.get(lastParent).right = tree.get(lastParent * 2 + 2); 30 // } 31 } 32 private static void preOrder(TreeNode node){ 33 if(node == null) return; 34 System.out.print(node.data + " "); 35 preOrder(node.left); 36 preOrder(node.right); 37 } 38 39 private static void inOrder(TreeNode node) { 40 if(node == null) return; 41 inOrder(node.left); 42 System.out.print(node.data + " "); 43 inOrder(node.right); 44 } 45 46 private static void postOrder(TreeNode node) { 47 if(node == null) return; 48 postOrder(node.left); 49 postOrder(node.right); 50 System.out.print(node.data + " "); 51 } 52 53 public static void main(String[] args) { 54 creatTree(); 55 TreeNode root = tree.get(0); 56 System.out.println("先序:"); 57 preOrder(root); 58 System.out.println(); 59 System.out.println("中序:"); 60 inOrder(root); 61 System.out.println(); 62 System.out.println("后序:"); 63 postOrder(root); 64 System.out.println(); 65 66 67 68 } 69 }
以arraylist为数组结构实现的一个完全二叉树,第n个结点的左孩子为2n+1,右孩子为2n+2