题目描述:有一棵二叉树,每个节点由一个大写字母标识(最多26个节点)。现有两组字母,分别表示后序遍历(左孩子·>右孩子->父节点)和中序遍历(左孩子·>父节点。
>右孩子)的结果,请输出层次遍历的结果。
输入描述:输入为两个字符串,分别是二叉树的后续遍历和中序遍历结果。
输出描述:输出二叉树的层次遍历结果。
补充说明:
示例
展开
示例1
输入:CBEFDA CBAEDF
输出:ABDCEF
说明:二叉树为:
A
B D
C E F
package com.example.kucun.controller;
import java.util.*;
class TreeNode{
char val;
TreeNode left;
TreeNode right;
public TreeNode(char val){
this.val=val;
}
}
public class Test {
private static int index=0;
private static String houxu;
private static Map<Character,Integer>map;
private TreeNode aa(int left,int right){
if(left>right){
//如果左边超出了右边 直接结束
return null;
}
if(index<0){
//如果索引位置出现了负数 直接结束
return null;
}
//获取后序遍历的最后一个节点 来当做根节点先开始
TreeNode root=new TreeNode(houxu.charAt(index));
index--;
//获取map中当前字符对应中序遍历的位置
int mid=map.get(root.val);
//从右半部分去找
root.right=aa(mid+1,right);
//从左半部分去找
root.left=aa(left,mid-1);
return root;
}
public static void main(String[] args) {
//后序遍历
String str1="CBEFDA";
//中序遍历
String str2="CBAEDF";
//给index赋值 默认是最后一位
index=str1.length()-1;
//后序遍历赋值
houxu=str1;
//先把中序遍历对应的位置 放入map中
map=new HashMap<>();
for (int i = 0; i <str2.length() ; i++) {
char c=str2.charAt(i);
map.put(c,i);
}
//从0到最后一位 递归去找
TreeNode node=new Test().aa(0,str2.length()-1);
getData(node);
}
private static void getData(TreeNode node){
if(node==null){
return;
}
//使用队列进行层序遍历
Queue<TreeNode>queue=new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()){
int size=queue.size();
for (int i = 0; i <size ; i++) {
//打印这一层的数据
TreeNode cur=queue.poll();
System.out.print(cur.val+" ");
//如果左右子树不为空 在放入到队列中
if(cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
}
System.out.println();
}
}
}