java中先序创建一棵树_根据先序和中序构建二叉树(java)后序输出

先序序列:   1,2,4,8,5,3,6,7

中序序列:   8,4,2,5,1,6,3,7

//节点类

/**

*

*/

package Tree;

/**

* @author 邢兵

* @data

* @description

*/

public class Node {

public Object data;

public Node left;

public Node right;

//创建一个空节点

public Node(){

this(null);

}

//创建一个没有孩子的节点

public Node(Object data){

this(data, null, null);

}

//创建一个 带有孩子的节点

public Node(Object data, Node left, Node right){

this.data = data;

this.left = left;

this.right = right;

}

}

/**

*

*/

package Tree;

/**

* @author 邢兵

* @data

* @description

*/

public class BiTree {

public static int index=0;

public static void main(String[] args) {

int pre[]={1,2,4,8,5,3,6,7};//先序排列

int in[] = {8,4,2,5,1,6,3,7};//中序排列

Node root = build(0, pre.length-1, pre, in);

post(root);

}

public static Node build(int left, int right, int preorder[], int inorder[]){

Node root = null;

if(left<=right){

int in = left;

for(int i=in;i<=right;i++){

if(inorder[i]==preorder[index]){

in = i;

break;

}

}

root = new Node(preorder[index]);

index++;

root.left = build(left, in-1, preorder, inorder);

root.right = build(in+1, right, preorder, inorder);

}

return root;

}

public static void post(Node root){

if(root!=null){

post(root.left);

post(root.right);

System.out.print(root.data);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值