HDu1710(二叉树)

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1710

更多介绍:http://blog.csdn.net/lhfight/article/details/7788291

 

package D0726;

import java.util.Scanner;

public class HDU1710 {

	static String str;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String[] strpre;//这里要用数组接受输入
		String[] strin;
		int n;
		while (sc.hasNext()) {
			n = sc.nextInt();
			strpre = new String[n];
			strin = new String[n];
			str = "";
			for (int i = 0; i < n; i++)
				strpre[i] = sc.next();
			for (int i = 0; i < n; i++)
				strin[i] = sc.next();
			Node3 node = buildTree(strpre, strin);
			postOrder(node);
			System.out.println(str.trim());
		}
	}

	// 建立二叉树
	public static Node3 buildTree(String[] strpre, String[] strin) {
		if (strpre.length <= 0)
			return null;

		// 建立一个根节点
		String s = strpre[0];
		Node3 root = new Node3(s);
		// 以根节点为中心,将中序分为两个子序列
		int i, index = 0;
		for (i = 0; i < strin.length; i++) {
			if (strin[i].equals(s)) {
				index = i;
				break;
			}
		}
		String[] leftin = new String[index];
		String[] rightin = new String[strin.length - index - 1];
		for (i = 0; i < index; i++)
			leftin[i] = strin[i];
		int j = index+1;
		for (i = 0; j < strin.length; i++,j++) 
			rightin[i] = strin[j];
		// 根所左中序的长度,将先序分为左右两个子先序
		int leftlen = leftin.length;
		String[] leftpre = new String[leftlen];
		String[] rightpre = new String[strpre.length - leftlen - 1];
		for (i = 0; i < leftlen; i++)
			leftpre[i] = strpre[i + 1];
		for (i = 0; i < strpre.length - leftlen - 1; i++)
			rightpre[i] = strpre[i + leftlen + 1];
		root.lChild = buildTree(leftpre, leftin);
		root.rChild = buildTree(rightpre, rightin);
		return root;
	}

	// 后序遍历
	public static void postOrder(Node3 node) {
		if (node != null) {
			postOrder(node.lChild);
			postOrder(node.rChild);
			str += " " + node.data;
		}
	}
}

class Node3 {
	public String data;
	public Node3 lChild;
	public Node3 rChild;

	public Node3(String data) {
		this.data = data;
		this.lChild = null;
		this.rChild = null;
	}
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怎么演

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值