From 115fe28b238fb32b3759f6aa57b0e23ae84cebdd Mon Sep 17 00:00:00 2001 From: chengleqi Date: Fri, 17 Dec 2021 21:21:27 +0800 Subject: [PATCH] =?UTF-8?q?update=200116.=E5=A1=AB=E5=85=85=E6=AF=8F?= =?UTF-8?q?=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87=E9=92=88.md=20C++?= =?UTF-8?q?=E7=89=88=E6=9C=AC=20=E4=B8=80=E7=A7=8D=E6=9B=B4=E7=AC=A6?= =?UTF-8?q?=E5=90=88=E6=A8=A1=E6=9D=BF=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D?= =?UTF-8?q?=E5=8E=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 29 +++++++------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index b6b723c9..1af0eaf0 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -87,7 +87,7 @@ public: 本题使用层序遍历是最为直观的,如果对层序遍历不了解,看这篇:[二叉树:层序遍历登场!](https://programmercarl.com/0102.二叉树的层序遍历.html)。 -层序遍历本来就是一层一层的去遍历,记录一层的头结点(nodePre),然后让nodePre指向当前遍历的节点就可以了。 +遍历每一行的时候,如果不是最后一个Node,则指向下一个Node;如果是最后一个Node,则指向nullptr。 代码如下: @@ -96,27 +96,18 @@ class Solution { public: Node* connect(Node* root) { queue que; - if (root != NULL) que.push(root); + if (root != nullptr) que.push(root); while (!que.empty()) { int size = que.size(); - vector vec; - Node* nodePre; - Node* node; - for (int i = 0; i < size; i++) { // 开始每一层的遍历 - if (i == 0) { - nodePre = que.front(); // 记录一层的头结点 - que.pop(); - node = nodePre; - } else { - node = que.front(); - que.pop(); - nodePre->next = node; // 本层前一个节点next指向本节点 - nodePre = nodePre->next; - } - if (node->left) que.push(node->left); - if (node->right) que.push(node->right); + for (int i = 0; i < size; ++i) { + Node* node = que.front(); + que.pop(); + if (i != size - 1) { + node->next = que.front(); //如果不是最后一个Node 则指向下一个Node + } else node->next = nullptr; //如果是最后一个Node 则指向nullptr + if (node->left != nullptr) que.push(node->left); + if (node->right != nullptr) que.push(node->right); } - nodePre->next = NULL; // 本层最后一个节点指向NULL } return root; }