当前位置:网站首页>【leetcode】199.二叉树的右视图
【leetcode】199.二叉树的右视图
2022-04-23 10:27:00 【前端corner】
题目
给定一个二叉树的 根节点 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
思路

- 想一想,从右往左看,看到的节点都有哪些特点呢?每一层都能且只能看到一个节点,且这个节点是每一层的最后一个节点。
- 根据上面的分析,很显然用二叉树的层序遍历就行了当遇到每一层的最后一个节点时,就把该节点添加到结果数组即可。
代码

/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
/** * @param {TreeNode} root * @return {number[]} */
var rightSideView = function(root) {
if(!root) return []
let queue = [root]
let res = []
while(queue.length){
const len = queue.length
for(let i = 0 ; i < len ; i++){
const curNode = queue.shift()
if(i === len - 1) res.push(curNode.val) //判断是否当层的最后一个节点,是的话就保存
if(curNode.left) queue.push(curNode.left)
if(curNode.right) queue.push(curNode.right)
}
}
return res
};
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
关注我的专栏,每天更新三道leetcode题解,一起变强!
版权声明
本文为[前端corner]所创,转载请带上原文链接,感谢
https://blog.csdn.net/laplacepoisson/article/details/124359162
边栏推荐
猜你喜欢

Operation of 2022 tea artist (primary) test question simulation test platform

景联文科技—专业数据标注公司和智能数据标注平台

Jinglianwen technology - professional data annotation company and intelligent data annotation platform

解决方案架构师的小锦囊 - 架构图的 5 种类型

微信小程序简介、发展史、小程序的优点、申请账号、开发工具、初识wxml文件和wxss文件

net start mysql MySQL 服务正在启动 . MySQL 服务无法启动。 服务没有报告任何错误。

0704、ansible----01

SSH uses private key to connect to server without key

101. Symmetric Tree

Arm debugging (1): two methods to redirect printf to serial port in keil
随机推荐
DBA common SQL statements (3) - cache, undo, index and wait events
Using idea to develop Spark Program
Chapter II in memory architecture (im-2.2)
部署jar包
lnmp的配置
DBA常用SQL语句(3)- cache、undo、索引和等待事件
mysql同一个表中相同数据怎么合并
任意文件读取漏洞 利用指南
349、两个数组的交集
C语言——自定义类型
Chapter 2 Oracle database in memory architecture (I) (im-2.1)
景联文科技—专业数据标注公司和智能数据标注平台
DBA常用SQL语句(4)- Top SQL
通过流式数据集成实现数据价值(4)-流数据管道
101. Symmetric Tree
Jerry's users how to handle events in the simplest way [chapter]
SSH利用私钥无密钥连接服务器踩坑实录
解决方案架构师的小锦囊 - 架构图的 5 种类型
MapReduce core and foundation demo
203. Remove linked list elements (linked list)
