当前位置:网站首页>【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
边栏推荐
猜你喜欢

Read LSTM (long short term memory)

2022 mobile crane driver test question bank simulation test platform operation

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

Solution architect's small bag - 5 types of architecture diagrams

【省选联考 2022 D2T1】卡牌(状态压缩 DP,FWT卷积)

JUC concurrent programming 09 -- source code analysis of condition implementation

SQL Server 递归查询上下级

Sim Api User Guide(6)

JUC concurrent programming 06 -- in-depth analysis of AQS source code of queue synchronizer

Yarn resource scheduler
随机推荐
Contact between domain name and IP address
MySql常用语句
101. Symmetric Tree
通过流式数据集成实现数据价值(5)- 流处理
Chapter 3 enable and adjust the size of IM column storage (im-3.1)
Sim Api User Guide(4)
DBA常用SQL语句(4)- Top SQL
Sim Api User Guide(5)
Read LSTM (long short term memory)
通过流式数据集成实现数据价值(5)- 流分析
Arbitrary file reading vulnerability exploitation Guide
Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022
ansible 云计算 自动化
Jinglianwen technology - professional data annotation company and intelligent data annotation platform
What about Jerry's stack overflow? [chapter]
142. Circular linked list||
24、两两交换链表中的节点(链表)
Realize data value through streaming data integration (2)
SSH uses private key to connect to server without key
Depth selector
