java 输出二叉树的右视图

牛客题目链接

1. 题目考点

  1. 根据先序和中序遍历数组重建二叉树
  2. 二叉树层次遍历过程中每层最后一个节点
  3. ArrayList 转换成 int[]

2. 考点解析

  1. 递归重建二叉树,每次递归前划分对应的先序和中序数组
// 使用 Arrays.copyOfRange 截取数组
public TreeNode reBuild(int[] xianxu, int[] zhongxu) {
        if (xianxu.length == 0 || zhongxu.length == 0) return null;
        TreeNode root = new TreeNode(xianxu[0]);
        int i = getIndex(zhongxu, xianxu[0]);
        int[] xianxul = Arrays.copyOfRange(xianxu, 1, i + 1);
        int[] xianxur = Arrays.copyOfRange(xianxu, i + 1, xianxu.length);
        int[] zhongxul = Arrays.copyOfRange(zhongxu, 0, i);
        int[] zhongxur = Arrays.copyOfRange(zhongxu, i + 1, zhongxu.length);
        // 递归重建左右子树
        root.left = reBuild(xianxul, zhongxul);
        root.right = reBuild(xianxur, zhongxur);
        return root;
    }
  1. 二叉树层次遍历获取每层最后一个节点
// 使用两个整数 curLevelCount 和 nextLevelCount当 curLevelCount = 0 时,此时出队节点为该层最后一个节点
public void bfs(TreeNode root, ArrayList<Integer> list) {
        if (root == null) return ;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // 开始只有根节点入队,curLevelCount = 1,下一层不清楚,nextLevelCount = 0
        int curLevelCount = 1, nextLevelCount = 0;
        while (!queue.isEmpty()) {
            root = queue.poll();
            curLevelCount -= 1;
            if (root.left != null) {
                queue.offer(root.left);
                nextLevelCount += 1;
            }
            if (root.right != null) {
                queue.offer(root.right);
                nextLevelCount += 1;
            } 
            // curLevelCount = 0 表示到达最后一个节点
            if (curLevelCount == 0) {
                list.add(root.val);
                curLevelCount = nextLevelCount;
                nextLevelCount = 0;
            }
        }
    }
  1. ArrayList 转化 int[],拆箱mapToInt()用 stream 流
ArrayList<Integer> list = new ArrayList<>();
int[] a = list.stream().mapToInt(k->k).toArray();
  1. int[] 转 ArrayList,装箱boxed()用 stream 流
int[] a = new int[]{1, 3, 4};
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
// IntStream().of(a).boxed().collect(Collectors.toList());

3. 参考链接

  1. int[] 转 ArrayList
  2. 牛客题目解析
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值