当前位置:网站首页>【JS解决】leedcode 117. 填充每个节点的下一个右侧节点指针 II
【JS解决】leedcode 117. 填充每个节点的下一个右侧节点指针 II
2022-06-13 04:36:00 【xiaozhangtxue】
题目要求:
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),‘#’ 表示每层的末尾。
JS代码
var connect = function(root) {
// 处理特殊情况
if (!root) return null
// 构建层次遍历的的数组
let arr = [root]
while(arr.length){
let n = arr.length
for(let i=0;i<n;i++){
// 抛出当前节点
let curNode = arr.shift()
// 如果是最后一个节点则指向null
if(i===n-1) curNode.next=null
// 如果不是最后一个节点,则指向下个节点(也就是arr中的第一个节点)
else curNode.next= arr[0]
// 继续遍历左右孩子
if(curNode.left!==null) arr.push(curNode.left)
if(curNode.right!==null) arr.push(curNode.right)
}
}
return root
};
运行结果
边栏推荐
- Applet waterfall flow
- 一致性哈希的简单认识
- February 25, 2021 (Archaeology 12 year Landbridge provincial competition)
- SS selector
- Ctfshow common postures (821-830)
- Click change color to change subscript
- Redis master-slave replication, sentinel mode, cluster
- Google Chrome browser reports an error: net:: err_ BLOCKED_ BY_ CLIENT
- 正态分布(高斯分布)
- The problem that ionic3 cannot automatically install the APK package
猜你喜欢
Colab tutorial (super detailed version) and colab pro/pro+ evaluation
2022 ICLR | CONTRASTIVE LEARNING OF IMAGE- AND STRUCTURE BASED REPRESENTATIONS IN DRUG DISCOVERY
Li Kou brush question 338 Bit count
Crawler scrapy framework learning 1
一致性哈希的简单认识
PowerShell:因为在此系统上禁止运行脚本,解决方法
【Try to Hack】upload-labs通关(暂时写到12关)
Ladder race
用navicat将mysql数据转化为postgresql
EMC rectification outline
随机推荐
电磁兼容常用名词术语
php开发博客系统的首页头部功能实现
Uni app Ali font icon does not display
Sword finger offer 56 - I. number of occurrences in the array
PowerShell:因为在此系统上禁止运行脚本,解决方法
力扣刷题647.回文子串
Analysis of the implementation principle of an open source markdown to rich text editor
The problem that ionic3 cannot automatically install the APK package
ACM ICPC
H5 the blue background color appears when clicking the picture
推荐的图片临时在线压缩工具
The data obtained from mongodb query data command is null
力扣刷题338.比特位计数
记录一次排查问题的经过——视频通话无法接起
Mongodb compass connects to the Alibaba cloud remote server database or reports an error occurred while loading instance info: command hostinfo req
【剑指Offer】面试题25.合并两个有序的链表
【Flutter 问题系列第 67 篇】在 Flutter 中使用 Get 插件在 Dialog 弹窗中不能二次跳转路由问题的解决方案
C盘无损移动文件
Idea Download
Tita:新锐集团采用一对一面谈推动绩效变革成功