package java;import java.util.ArrayDeque;public class BinaryTree {static class TreeNode{ int value; TreeNode left; TreeNode right;public TreeNode(int value){ this.value=value; } }TreeNode root;public BinaryTree(int[] array){ root=makeBinaryTreeByArray(array,1); } public static TreeNode makeBinaryTreeByArray(int[] array,int index){ if(index<array.length){ int value=array[index]; if(value!=0){ TreeNode t=new TreeNode(value); array[index]=0; t.left=makeBinaryTreeByArray(array,index*2); t.right=makeBinaryTreeByArray(array,index*2+1); return t; } } return null; }public void preOder(){ //先根遍历算法 if(root==null){ System.out.println("empty tree"); return; } else{ System.out.println(root.data.toString()+""); preOder(root.left); preOder(root.right); } }public void inOder(){ //中根遍历算法 if(root==null){ System.out.println("empty tree"); return; } else{ inOder(root.left); System.out.println(root.data.toString()+""); inOder(root.right); } }public void postOder(){ //后根遍历算法 if(root==null){ System.out.println("empty tree"); return; } else{ postOder(root.left); postOder(root.right); System.out.println(root.data.toString()+""); } }public static void main(String[] args) { int[] arr1={0,13,65,5,97,25,0,37,22,0,4,28,0,0,32,0}; int[] arr2={0,2,3,4,5,6,6,7,9,5,7,4,3,2,2,4,5,5,6,4}; int[] arr3={6,6,4,8,4,9,4,9,3,6,3,7,2,4,6,3,4,2,5,2}; BinaryTree tree=new BinaryTree(arr1); BinaryTree tree1=new BinaryTree(arr2); BinaryTree tree2=new BinaryTree(arr3); tree. preOder(); tree.inOder(); tree.postOder(); tree1. preOder(); tree1.inOder(); tree1.postOder(); tree2. preOder(); tree2.inOder(); tree2.postOder();}}
添加回答
举报
0/150
提交
取消