java根据先序和中序求后序,java实现数据结构之根据先序中序找后序

首先建立节点类

public class TreeNode1 {

public String data; //数据元素

public TreeNode1 left, right; //指向左,右孩子节点的链

public TreeNode1() {

this("?");//将问号做为值传入

}

public TreeNode1(String d) {

data = d;

left = right = null;

}

public void perorder(TreeNode1 p) {//每一次调用的节点都是根节点

if (p != null) {

System.out.print(p.data + " ");

perorder(p.left);

perorder(p.right);

}

}

public void inorder(TreeNode1 p) {

if (p != null) {

perorder(p.left);

System.out.print(p.data + " ");

perorder(p.right);

}

}

public void postorder(TreeNode1 p) {

if (p != null) {

perorder(p.left);

perorder(p.right);

System.out.print(p.data + " ");

}

}

}

//构造树

public class Tree1 {

protected TreeNode1 root;

public Tree1() {//构造空树

root = null;

}

public Tree1(String perstr, String instr) {

root = enter(perstr, instr);

}

public void preorderTraversal() {

System.out.println("先根遍历");

if (root != null) {

root.perorder(root);

System.out.println();

}

}

public void inorderTraversal() {

System.out.println("中根遍历");

if (root != null) {

root.inorder(root);

System.out.println();

}

}

public void postorderTraversal() {

System.out.println("后根遍历");

if (root != null) {

root.postorder(root);

System.out.println();

}

}

public TreeNode1 enter(String prestr, String instr) {

TreeNode1 p = null;

int k, n;

String first, presub, insub;

n = prestr.length();

if (n > 0) {

System.out.print("prestr=" + prestr + "\t instr" + instr);

first = prestr.substring(0, 1);

// System.out.println("第一个元素为:" + first);

p = new TreeNode1(first);

k = instr.indexOf(first);

// System.out.println("k在中序遍历中的位置:" + k);

System.out.println("\t first" + first + "\t k" + k);

presub = prestr.substring(1, k + 1);

insub = instr.substring(0, k);

p.left = enter(presub, insub);

presub = prestr.substring(k + 1, n);

insub = instr.substring(k + 1, n);

p.right = enter(presub, insub);

}

return p;

}

}

//测试类

public class Tree1_ex {

public static void main(String[] args) {

String prestr="ABDGCEFH";

String instr="DGBAECHF";

if(args.length>1){

prestr=args[0];

instr=args[1];

}

Tree1 t1=new Tree1(prestr,instr);

t1.preorderTraversal();

t1.inorderTraversal();

t1.postorderTraversal();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值