为了账号安全,请及时绑定邮箱和手机立即绑定

利用java写先根中根和后根的遍历程序怎么写,我这样写好像有问题啊,求老师帮忙~~急急急

利用java写先根中根和后根的遍历程序怎么写,我这样写好像有问题啊,求老师帮忙~~急急急

小城姑娘 2015-05-18 16:12:29
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 回答
  • 0 关注
  • 2352 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信