199. 二叉树的右视图-字节跳动高频题

248 篇文章 2 订阅
232 篇文章 0 订阅

一、题目描述

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

示例 1:

在这里插入图片描述

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

二、解题

BFS

这题使用广度优先遍历,层次遍历,遍历每一层,将最后一个数据保存就是需要的返回集合。

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //层次遍历,每层入队列,取队列的最后一个值即可。
        //BFS
        
        Deque<TreeNode> queue = new LinkedList<>();
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        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);
                }
            }
        }
        return res;
    }
}
DFS

DFS没有BFS那样好理解,按照根节点-右子树-左子树的顺序访问,保证每层访问的第一个节点是最右边的节点即可。

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        //DFS 
        List<Integer> res = new ArrayList<>();
        if(root == null){
            return res;
        }
        dfs(root,0,res);
        return res;
    }
    public void dfs(TreeNode root,int depth,List<Integer> res){
        if(root == null){
            return;
        }
        if(depth == res.size()){
            res.add(root.val);
        }
        depth++;
        dfs(root.right,depth,res);
        dfs(root.left,depth,res);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值