用java实现的数组创建二叉树以及先序遍历,中序遍历,后序遍历三种遍历
package myTest; import java.awt.Checkbox; import java.util.LinkedList; import java.util.List; public class myClass { public static void main(String[] args) { // TODO Auto-generated method stub myClass tree = new myClass(); int[] datas = new int[]{1,2,3,4,5,6,7,8,9}; List<Node> nodelist = new LinkedList<>(); tree.creatBinaryTree(datas, nodelist); Node root = nodelist.get(0); System.out.println("先序遍历:"); tree.preOrderTraversal(nodelist, root); System.out.println(); System.out.println("中序遍历:"); tree.inOrderTraversal(nodelist, root); System.out.println(); System.out.println("后序遍历:"); tree.postOrderTraversal(nodelist, root); } /** * * @param datas 实现二叉树各节点值的数组 * @param nodelist 二叉树list */ private void creatBinaryTree(int[] datas,List<Node> nodelist){ //将数组变成node节点 for(int nodeindex=0;nodeindex<datas.length;nodeindex++){ Node node = new Node(datas[nodeindex]); nodelist.add(node); } //给所有父节点设定子节点 for(int index=0;index<nodelist.size()/2-1;index++){ //编号为n的节点他的左子节点编号为2*n 右子节点编号为2*n+1 但是因为list从0开始编号,所以还要+1 //这里父节点有1(2,3),2(4,5),3(6,7),4(8,9) 但是最后一个父节点有可能没有右子节点 需要单独处理 nodelist.get(index).setLeft(nodelist.get(index*2+1)); nodelist.get(index).setRight(nodelist.get(index*2+2)); } //单独处理最后一个父节点 因为它有可能没有右子节点 int index = nodelist.size()/2-1; nodelist.get(index).setLeft(nodelist.get(index*2+1)); //先设置左子节点 if(nodelist.size() % 2 == 1){ //如果有奇数个节点,最后一个父节点才有右子节点 nodelist.get(index).setRight(nodelist.get(index*2+2)); } } /** * 遍历当前节点的值 * @param nodelist * @param node */ public void checkCurrentNode(List<Node> nodelist,Node node){ System.out.print(node.getVar()+" "); } /** * 先序遍历二叉树 * @param root 二叉树根节点 */ public void preOrderTraversal(List<Node> nodelist,Node node){ if (node == null) //很重要,必须加上 当遇到叶子节点用来停止向下遍历 return; checkCurrentNode(nodelist,node); preOrderTraversal(nodelist,node.getLeft()); preOrderTraversal(nodelist,node.getRight()); } /** * 中序遍历二叉树 * @param root 根节点 */ public void inOrderTraversal(List<Node> nodelist,Node node){ if (node == null) //很重要,必须加上 return; inOrderTraversal(nodelist, node.getLeft()); checkCurrentNode(nodelist,node); inOrderTraversal(nodelist, node.getRight()); } /** * 后序遍历二叉树 * @param root 根节点 */ public void postOrderTraversal(List<Node> nodelist,Node node){ if (node == null) //很重要,必须加上 return; postOrderTraversal(nodelist, node.getLeft()); postOrderTraversal(nodelist, node.getRight()); checkCurrentNode(nodelist,node); } /** * 节点类 * var 节点值 * left 节点左子节点 * right 右子节点 */ class Node{ int var; Node left; Node right; public Node(int var){ this.var = var; this.left = null; this.right = null; } public void setLeft(Node left) { this.left = left; } public void setRight(Node right) { this.right = right; } public int getVar() { return var; } public void setVar(int var) { this.var = var; } public Node getLeft() { return left; } public Node getRight() { return right; } } }