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

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

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();

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值