根据二叉树前序和中序结果建立二叉树,并输出右视图

本文介绍如何利用给定的二叉树前序遍历和中序遍历,通过递归算法重建二叉树,并重点展示如何获取并输出二叉树的右视图。通过实例演示了如何在Java中实现这一过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型一维数组 先序遍历
     * @param zhongxu int整型一维数组 中序遍历
     * @return int整型一维数组
     */
    
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int value) {
            this.val = value;
        }
    }
    public int[] solve (int[] xianxu, int[] zhongxu) {
        // write code here
        int len = xianxu.length;
        TreeNode root = buildTree(xianxu, 0, len - 1, zhongxu, 0, len - 1);
        Queue<TreeNode> queue = new LinkedList<>();
        ArrayList<Integer> res = new ArrayList<>();
        queue.add(root);
        while (! queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (i == size - 1) {
                    res.add(node.val);
                }
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        int[] list = new int[res.size()];
        for (int i = 0; i < res.size(); i++) {
            list[i] = res.get(i);
        }
        return list;
    }
    
    private TreeNode buildTree(int[] xianxu, int startOfPre, int endOfPre, int[] zhongxu, int startOfIn, int endOfIn) {
        if (startOfPre > endOfPre || startOfIn > endOfIn) return null;
        TreeNode root = new TreeNode(xianxu[startOfPre]);
        int index = startOfIn;
        while (index <= endOfIn && zhongxu[index] != xianxu[startOfPre]) {
            index++;
        }
        root.left = buildTree(xianxu, startOfPre + 1, startOfPre + index - startOfIn, zhongxu, startOfIn, index - 1);
        root.right = buildTree(xianxu, startOfPre + index - startOfIn + 1, endOfPre, zhongxu, index + 1, endOfIn);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值