From adcfdd63d6c5c447c6cccb81f9dae696a05a3795 Mon Sep 17 00:00:00 2001 From: Jack <965555169@qq.com> Date: Mon, 9 Aug 2021 10:12:06 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0116.=20=E5=A1=AB=E5=85=85?= =?UTF-8?q?=E6=AF=8F=E4=B8=AA=E8=8A=82=E7=82=B9=E7=9A=84=E4=B8=8B=E4=B8=80?= =?UTF-8?q?=E4=B8=AA=E5=8F=B3=E4=BE=A7=E8=8A=82=E7=82=B9=E6=8C=87=E9=92=88?= =?UTF-8?q?-JavaScript?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index 28e6f645..6feb1ca9 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -130,21 +130,47 @@ public: ## Java ```java + ``` ## Python ```python + ``` ## Go ```go + ``` ## JavaScript ```js +const connect = root => { + if (!root) return root; + // 根节点入队 + const Q = [root]; + while (Q.length) { + const len = Q.length; + // 遍历这一层的所有节点 + for (let i = 0; i < len; i++) { + // 队头出队 + const node = Q.shift(); + // 连接 + if (i < len - 1) { + // 新的队头是node的右边元素 + node.next = Q[0]; + } + // 队头左节点有值,放入队列 + node.left && Q.push(node.left); + // 队头右节点有值,放入队列 + node.right && Q.push(node.right); + } + } + return root; +}; ``` -----------------------