(二叉搜索树10.1.2)POJ 1577 Falling Leaves(根据删除叶子节点的顺序输出计算一颗二叉树的前序遍历序列)

package com.njupt.acm;

import java.util.Scanner;

public class POJ_1577 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int levels = 0;
		String line;
		String[] leaves = new String[26];
		
		while(scanner.hasNext()){
			line = scanner.nextLine().trim();
			if(line.equals("*")){
				System.out.println(preorder(leaves, levels));
				leaves = new String[26];
				levels = 0;
			}else if(line.equals("$")){
				System.out.println(preorder(leaves, levels));
				break;
			}else{
				leaves[levels++] = line;
			}
		}
		
	}
	
	public static String preorder(String[] leaves,int levels){//将根据leaves中的行序列计算前序遍历序列
		
		while(levels > 0 && leaves[levels-1].length() == 0){//从leaves[]标的最后一项开始找,找到第一个非空项..
			levels--;
		}
		if(levels == 0){
			return "";
		}
		levels--;
		
		char root = leaves[levels].charAt(0);//leaves表尾存储子根
		String[] left = new String[levels];
		String[] right = new String[levels];
		
		int i;
		for(i = 0 ; i < levels ; ++i){
			int past = 0;
			while(past < leaves[i].length() && leaves[i].charAt(past) < root){//找到左右子树的分界点
				past++;
			}
			
			left[i] = leaves[i].substring(0,past);
			right[i] = leaves[i].substring(past);
		}
		
		return root + preorder(left, levels) + preorder(right, levels);
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

帅气的东哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值