输出二叉树的右视图

[牛客算法总结]:标题
  

标签:

二叉树、DFS、先序遍历、中序遍历、递归、队列
 

题目:

请根据二叉树的前序遍历,中序遍历恢复二叉树,并打印出二叉树的右视图。
如输入[1,2,4,5,3],[4,2,5,1,3]时,通过前序遍历的结果[1,2,4,5,3]和中序遍历的结果[4,2,5,1,3]可重建出以下二叉树:
请添加图片描述

所以对应的输出为[1,3,5]。
 

反思:个人思考

所谓右视图,指的是每层的最后一个。二叉树每层,需要使用BFS,使用到队列来解决。

具体过程
重建二叉树看我上一篇博客:重建二叉树
然后再通过BFS输出每层最后一个即可。

 

用到的知识点:

二叉树、DFS、先序遍历、中序遍历、递归、队列

 

代码:代码内容

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 求二叉树的右视图
     * @param xianxu int整型一维数组 先序遍历
     * @param zhongxu int整型一维数组 中序遍历
     * @return int整型一维数组
     */
    List<Integer> arrayList = new ArrayList();
    public int getRootIndexInOrder(int[] xianxu, int[] zhongxu) {
        for (int i = 0; i < zhongxu.length; i++) {
            if (xianxu[0] == zhongxu[i]) return i;
        }
        return -1;
    }

    public TreeNode getRightTree(int[] xianxu, int[] zhongxu) {
        // write code here
        if (xianxu == null || xianxu.length == 0) return null;
        int preLength = xianxu.length;
        int inOrderLength = zhongxu.length;
        // 创建树根
        TreeNode root = new TreeNode(xianxu[0]);

        int index = getRootIndexInOrder(xianxu, zhongxu);
        // 先序:[1,2,4,5,3]
        // 中序:[4,2,5,1,3]
        root.left = getRightTree(
                        Arrays.copyOfRange(xianxu, 1, index + 1),
                        Arrays.copyOfRange(zhongxu, 0, index)
                    );
        root.right = getRightTree(
                         Arrays.copyOfRange(xianxu, index + 1, preLength),
                         Arrays.copyOfRange(zhongxu, index + 1, inOrderLength)
                     );
        return root;
    }

    public void getRightViewList(TreeNode root) {
        if (root == null) return;
        Queue<TreeNode> queue = new LinkedList();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- != 0) {
                TreeNode poll = queue.poll();
                if (poll.left != null) {
                    queue.add(poll.left);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                }
                if (size == 0) arrayList.add(poll.val);
            }
        }
    }

    public int[] solve (int[] xianxu, int[] zhongxu) {
        TreeNode root = getRightTree(xianxu, zhongxu);
        getRightViewList(root);
        return arrayList.stream().mapToInt(Integer::intValue).toArray();
    }
    
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值