L2-035 完全二叉树的层序遍历 (25 分) java 题解

一个二叉树,如果每一个层的结点数都达到最大值,则这个二叉树就是完美二叉树。对于深度为 D 的,有 N 个结点的二叉树,若其结点对应于相同深度完美二叉树的层序遍历的前 N 个结点,这样的树就是完全二叉树

给定一棵完全二叉树的后序遍历,请你给出这棵树的层序遍历结果。

输入格式:

输入在第一行中给出正整数 N(≤30),即树中结点个数。第二行给出后序遍历序列,为 N 个不超过 100 的正整数。同一行中所有数字都以空格分隔。

输出格式:

在一行中输出该树的层序遍历序列。所有数字都以 1 个空格分隔,行首尾不得有多余空格。

输入样例:

8
91 71 2 34 10 15 55 18

输出样例:

18 34 55 71 2 10 15 91

解题思路:

由于二叉树为完全二叉树,所以可以用基于数组的顺序存储法。题中给出的数组为后序遍历,求层序遍历。可以在模拟一个新数组的后序遍历时,将给出的数组值依次赋给新数组。代码简单,思路不容易想到。

java代码:

import java.io.*;

public class Main {
	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(br.readLine());
		int []arr = new int[n + 1];
		String[] split = br.readLine().split(" ");
		for(int i = 0; i < split.length;i++) {
			arr[i] = Integer.parseInt(split[i]);
		}
		T035 temp = new T035(n, arr);
		temp.print();
	}
}
class T035{
	int n;
	int []arr;//答案数组
	int []temp;//存储题给出的数组
	int i = 0;

	public T035(int n,int[] a) {
		this.n = n;
		arr = new int[n + 1];
		temp = a;
	}
	
	public void travel(int m) {
		if(m > n)
			return ;
		travel(2 * m);
		travel(2 * m + 1);
		arr[m] = temp[i++];
	}
	
	public void print() {
		travel(1);
		StringBuilder builder = new StringBuilder();
		for(int j = 1;j < arr.length;j++) {
			builder.append(arr[j] + " ");
		}
		System.out.println(builder.toString().trim());
	}
}

PTA提交截图:

Java代码:

import java.io.*;

public class Main{
	static StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
	public static int ini() throws IOException {
		st.nextToken();
		return (int)st.nval;
	}
	static int N = 35, n, idx;
	static int []w = new int[N];
	static int []tr = new int[N];
	
	public static void main(String[] args) throws IOException {
		n = ini();
		for(int i = 0; i < n; i++) w[i] = ini();
		
		dfs(1);
		System.out.print(tr[1]);
		for(int i = 2; i <= n; i++) System.out.print(" " + tr[i]);
	}
	
	public static void dfs(int u) {
		if(u > n) return;
		dfs(u * 2);
		dfs(u * 2 + 1);
		tr[u] = w[idx++];
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值