acm编程 二叉树的广度优先遍历

题目描述:有一棵二叉树,每个节点由一个大写字母标识(最多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();
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值