leetcode199. 二叉树的右视图(java)

265 篇文章 2 订阅
235 篇文章 0 订阅

leetcode199. 二叉树的右视图

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-right-side-view

题目描述

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例1:
在这里插入图片描述
输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

示例 2:
输入: [1,null,3]
输出: [1,3]

示例 3:
输入: []
输出: []

提示:
二叉树的节点个数的范围是 [0,100]
-100 <= Node.val <= 100

广度优先遍历

对二叉树进行深度优先遍历,每遍历一层,记录当前层的最右侧节点.
最后输出最右侧节点,就是答案了.

代码演示

  public static class TreeNode{
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
      }
    }

 /**
     * 宽度优先遍历
     * @param root
     * @return
     */
    public static List<Integer> rightSideView(TreeNode root) {
        if (root == null){
            return null;
        }
        //记录每层的最右侧节点
        HashMap<Integer, Integer> rightViewMap = new HashMap<>();
        //先进后出的队列,进行宽度优先遍历
        Deque<TreeNode> nodeStacks = new LinkedList<>();
        //记录节点所在的层
        Deque<Integer> depthStacks = new LinkedList<>();
        //root节点先加进去
        nodeStacks.push(root);
        //第一层是0
        depthStacks.push(0);
        //记录最大深度
        int maxDepth = -1;
        while (!nodeStacks.isEmpty()){
            //弹出节点
            TreeNode cur = nodeStacks.pop();
            //弹出深度
            Integer depth = depthStacks.pop();
            //更新最大深度
            maxDepth = Math.max(maxDepth,depth);
            if (cur != null){
                //保存最右侧节点,
                if (!rightViewMap.containsKey(depth)){
                    rightViewMap.put(depth,cur.val);
                }
                if (cur.left != null){
                    nodeStacks.push(cur.left);
                    depthStacks.push(depth + 1);
                }
                if (cur.right != null){
                    nodeStacks.push(cur.right);
                    depthStacks.push(depth + 1);
                }
            }


        }

        ArrayList<Integer> ans = new ArrayList<>();
        for (int i = 0; i <= maxDepth;i++ ){
            ans.add(rightViewMap.get(i));
        }
        return ans;
    }

二叉树专题

leetcode109. 有序链表转换二叉搜索树

leetcode652. 寻找重复的子树

leetcode450. 删除二叉搜索树中的节点

leetcode701. 二叉搜索树中的插入操作

leetcode98. 验证二叉搜索树

leetcode700. 二叉搜索树中的搜索

leetcode95–不同的二叉搜索树 II

leetcode96–不同的二叉搜索树

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值