当前位置:网站首页>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);
}
}
边栏推荐
- 【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
- 2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
- tidyverse笔记——dplyr包
- CHI论文阅读(1)EmoGlass: an End-to-End AI-Enabled Wearable Platform for Enhancing Self-Awareness of Emoti
- Analysis of pseudo-classes and pseudo-elements
- 那些破釜沉舟入局Web3.0的互联网精英都怎么样了?
- 线程唤醒机制
- 基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
- DirectExchange switch simple introduction demo
- leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
猜你喜欢

Leetcode952. 按公因数计算最大组件大小

LeetCode刷题——摆动序列#376#Medium

2022.07.18_每日一题

LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】

Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record

360 push-360 push tool-360 batch push tool

毫米波技术基础

【网络攻防】常见的网络攻防技术——黑客攻防(通俗易懂版)

【面试:并发篇38:多线程:线程池】ThreadPoolExecutor类的基本概念

DAY18:XSS 漏洞
随机推荐
电脑开机密码怎么设置?如何给你的电脑加上“安全锁”
简单谈谈Feign
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
2022.07.24_每日一题
leetcode 406. Queue Reconstruction by Height
嵌入式系统驱动初级【2】——内核模块下_参数和依赖
2022.07.12_每日一题
2022.07.20_每日一题
SQL Server Datetime2数据类型
2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)
Gradle剔除依赖演示
MySQL的触发器
强化学习科研知识必备(数据库、期刊、会议、牛人)
线程唤醒机制
postgresql源码学习(34)—— 事务日志⑩ - 全页写机制
Log4net 思维导图
QFileInfo常规方法
SQLite数据库连接字符串
第十六章:构建n(5,7)阶素数幻方
庐山谣寄卢侍御虚舟