当前位置:网站首页>2022.07.26_Daily Question
2022.07.26_Daily Question
2022-07-31 07:40:00 【No. い】
116. 填充每个节点的下一个右侧节点指针
题目描述
- 填充每个节点的下一个右侧节点指针
给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点.二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点.如果找不到下一个右侧节点,则将 next 指针设置为 NULL.
初始状态下,所有 next 指针都被设置为 NULL.
示例 1:
输入:root = [1,2,3,4,5,6,7]
输出:[1,#,2,3,#,4,5,6,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示.序列化的输出按层序遍历排列,同一层节点由 next 指针连接,'#' 标志着每一层的结束.
示例 2:
输入:root = []
输出:[]
提示:
树中节点的数量在 [0, 212 - 1] 范围内
-1000 <= node.val <= 1000
进阶:
你只能使用常量级额外空间.
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度.
coding
/* // Definition for a Node. class Node { public int val; public Node left; public Node right; public Node next; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right, Node _next) { val = _val; left = _left; right = _right; next = _next; } }; */
class Solution {
// Borrowed from next preorder traversal
// next There are two pointers
// 1
// 2 3
// 4 5 6 7
// 第一种: 2 -> 3 Just let the left child of the head node point to the right child
// 第二种: 5 -> 6 Two subtrees are left and right child direct pointers, Head nodes can be used 2 的 next 指针指向 3, 然后 5 指向 3 的左孩子即可
public Node connect(Node root) {
preOrderRecur(root);
return root;
}
public void preOrderRecur(Node node) {
if (node == null) {
return;
}
if (node.left != null) {
node.left.next = node.right;
node.right.next = node.next == null ? null : node.next.left;
}
preOrderRecur(node.left);
preOrderRecur(node.right);
}
}
边栏推荐
猜你喜欢
解决win11/win10在登陆界面(解锁界面)点击获取每日壁纸无效的问题 - get Daily Lockscreen and Wallpaper - Win11/10的登录界面背景图片在哪里?

电压源的电路分析知识分享

《白帽子说Web安全》思维导图

Redux state management

360推送-360推送工具-360批量推送工具

从入门到一位合格的爬虫师,这几点很重要

2022.07.18_每日一题

【C语言项目合集】这十个入门必备练手项目,让C语言对你来说不再难学!

One of the small practical projects - food alliance ordering system

PCB抄板
随机推荐
Install the gstreamer development dependency library to the project sysroot directory
任务及任务切换
外贸网站优化-外贸网站优化教程-外贸网站优化软件
LeetCode brush # 376 # Medium - swing sequence
HighTec 的安装与配置
Database Principles Homework 3 — JMU
tidyverse笔记——dplyr包
基金投顾业务
‘vite‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
批量翻译软件免费【2022最新版】
Analysis of the implementation principle and detailed knowledge of v-model syntactic sugar and how to make the components you develop support v-model
R——避免使用 col=0
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
nohup原理
【C语言项目合集】这十个入门必备练手项目,让C语言对你来说不再难学!
Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
【微服务】(十六)—— 分布式事务Seata
2.(1)栈的链式存储、链栈的操作(图解、注释、代码)
Run the NPM will pop up to ask "how are you going to open this file?"
剑指offer(一)