package com.cooper.binarytree; import java.util.ArrayList; import java.util.List; /** * @author 10400 * @create 2018-06-14 17:53 */ public class BinaryTree { //根节点 private TreeNode root; //存放树节点 private List> list; /** * 树节点 */ class TreeNode{ TreeNode left; TreeNode right; E e; public TreeNode(TreeNode left,TreeNode right,E e){ this.e = e; this.left = left; this.right = right; } } /** * 获取根节点元素内容 * @return */ public E getRootElement(){ return root.e; } /** * 通过数组创建树，转换规则：依次为节点列表中的左右孩子赋值。 * 左子树 = 2*i + 1 * 右子树 = 2*i + 2 * @return */ public void createBTreeByArray(E[] array){ list = new ArrayList<>(); for (E e: array) { TreeNode treeNode = new TreeNode<>(null,null,e); list.add(treeNode); } //初始化对象树 for(int i = 0; i < (array.length/2) ; i++){ list.get(i).left = list.get(2 * i + 1); list.get(i).right = list.get(2 * i + 2); } } /** * 先序遍历 */ public void indorder(TreeNode root){ if(root == null){ return; } System.out.println("data = " + root.e); indorder(root.left); //递归输出左子树 indorder(root.right);//递归输出右子树 } /** * 中序遍历 * @param root */ public void inOrderTraverse(TreeNode root){ if(root == null){ return; } inOrderTraverse(root.left); System.out.println("data = " + root.e); inOrderTraverse(root.right); } /** * 后续遍历 * @param root */ public void postOrderTraverse(TreeNode root){ if(root == null){ return; } postOrderTraverse(root.left); postOrderTraverse(root.right); System.out.println("data " + root.e); } public static void main(String[] args) { BinaryTree binaryTree = new BinaryTree<>(); binaryTree.createBTreeByArray(new Integer[]{1,2,3,4,5,6,7,8,9}); System.out.println(" 先序遍历：" ); binaryTree.indorder(binaryTree.list.get(0)); System.out.println(" 中序遍历：" ); binaryTree.inOrderTraverse(binaryTree.list.get(0)); System.out.println(" 后序遍历：" ); binaryTree.postOrderTraverse(binaryTree.list.get(0)); } }