专业建站公司报价单,手机网站制作平台有哪些,网站建设技术简易留言板,短视频素材哪里找117. 填充每个节点的下一个右侧节点指针 II
难度#xff1a;中等
题目
给定一个二叉树#xff1a;
struct Node {int val;Node *left;Node *right;Node *next;
}填充它的每个 next 指针#xff0c;让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点#xff0c…117. 填充每个节点的下一个右侧节点指针 II
难度中等
题目
给定一个二叉树
struct Node {int val;Node *left;Node *right;Node *next;
}填充它的每个 next 指针让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点则将 next 指针设置为 NULL 。
初始状态下所有 next 指针都被设置为 NULL 。
示例 1 输入root [1,2,3,4,5,null,7]
输出[1,#,2,3,#,4,5,7,#]
解释给定二叉树如图 A 所示你的函数应该填充它的每个 next 指针以指向其下一个右侧节点如图 B 所示。序列化输出按层序遍历顺序由 next 指针连接# 表示每层的末尾。示例 2
输入root []
输出[]提示
树中的节点数在范围 [0, 6000] 内-100 Node.val 100
进阶
你只能使用常量级额外空间。使用递归解题也符合要求本题中递归程序的隐式栈空间不计入额外空间复杂度
个人题解
思路
考虑逐层遍历考虑用一个list来充当层的概念每次遍历当前层的时候把下一层的节点先装到list中则当list中没有节点时表示所有节点遍历完毕有节点则继续遍历遍历时用一个指针完成next的赋值将当前层节点串起来
class Solution {
public Node connect(Node root) {if (root null) {return null;}ArrayListNode list new ArrayList();list.add(root);while (!list.isEmpty()) {ArrayListNode nextList new ArrayList(); // 记录下一层遍历的节点Node curNode null; // 用于连接for (Node node : list) {if (node.left ! null) {nextList.add(node.left);if (curNode ! null) {curNode.next node.left;}curNode node.left;}if (node.right ! null) {nextList.add(node.right);if (curNode ! null) {curNode.next node.right;}curNode node.right;}}list nextList;}return root;}
}进阶
上面层的概念是用list来表示的分析一下 如果用一个指针指向下一层的头节点即可得到每层遍历的起点再考虑用一个尾指针表示下一层的尾节点则遍历当前层时即可将下一层的节点接在尾节点上 经过上述分析遍历过程不再需要list容器只需要3个指针即可当前层遍历指针下一层头指针及下一层尾指针每次遍历完当前层将下一层头指针及尾指针重置
class Solution {public Node connect(Node root) {Node curTail root;Node nextHead null;Node nextTail null;while (curTail ! null) {// 看左子结点if (curTail.left ! null) {if (nextTail ! null) {nextTail.next curTail.left;} else {nextHead curTail.left;}nextTail curTail.left;}// 看右子结点if (curTail.right ! null) {if (nextTail ! null) {nextTail.next curTail.right;} else {nextHead curTail.right;}nextTail curTail.right;}if (curTail.next ! null) {// 继续当前层遍历curTail curTail.next;} else {// 当前层遍历完毕开启下一层遍历将下一层指针重置curTail nextHead;nextHead null;nextTail null;}}return root;}
}其他非官方题解
class Solution {public Node connect(Node root) {Node cur root;while (cur ! null) {Node dummy new Node(0);Node p dummy;while (cur ! null) {if (cur.left ! null) {p.next cur.left;p p.next;}if (cur.right ! null) {p.next cur.right;p p.next;}cur cur.next;}cur dummy.next;}return root;}
}