UVa699-The Falling Leaves(下落的叶子)

UVa 699 – The Falling Leaves(下落的叶子)

给一棵二叉树,每个节点都有一个水平位置:左子节点在它左边1个单位,右子节点在右边一个单位。从左向右输出每个水平位置的所有节点的权值之和。按照递归(先序)方式输入,用-1表示空树。
样例输入:
5 7 -1 6 -1 -1 3 -1 -1
8 2 9 -1 -1 6 5 -1 -1 12 -1 -1 3 7 -1 -1 -1
-1
样例输出
case1:7 11 3
case2:9 7 21 15

import java.util.Scanner;

public class Test
{
	static int[] sum = new int[1000]; //全局变量
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		int p = 0;
		while (root())
		{
			while (sum[p]==0)	p++;  //找最左边的叶子
			System.out.print("case: ");
			while (sum[p]!=0)
				System.out.print(sum[p++]+" "); //输出
			System.out.println();
		}
	}// main
	//边输入边统计
	private static boolean root(){
		Scanner cin = new Scanner(System.in);
		int v = cin.nextInt();
		if (v==-1) return false;
		//初始化数组
		for (int i = 0;i<sum.length;i++)
			sum[i]=0;
		//该树的水平位置,500作为根的初始位置
		int pos = sum.length>>1;
		sum[pos]=v;
		build(pos-1);build(pos+1);
		
		return true;
	}//root
	//输入并统计一棵子树,树根的水平位置为p
	private static void build(int p){
		Scanner cin = new Scanner(System.in);
		int v = cin.nextInt();
		if(v==-1) return; //空树
		sum[p]+=v;
		build(p-1);build(p+1);
	}//build
}
	

点赞