From 58ffbd146ba7250eba350b688f2bed095495e012 Mon Sep 17 00:00:00 2001 From: leeeeeeewii <54872662+leeeeeeewii@users.noreply.github.com> Date: Tue, 1 Mar 2022 23:40:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=200116.=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?.md=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...个节点的下一个右侧节点指针.md | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/problems/0116.填充每个节点的下一个右侧节点指针.md b/problems/0116.填充每个节点的下一个右侧节点指针.md index bc3a8c6b..2c443de5 100644 --- a/problems/0116.填充每个节点的下一个右侧节点指针.md +++ b/problems/0116.填充每个节点的下一个右侧节点指针.md @@ -211,9 +211,52 @@ class Solution: return root ``` ## Go - ```go - +// 迭代法 +func connect(root *Node) *Node { + if root == nil { + return root + } + stack := make([]*Node, 0) + stack = append(stack, root) + for len(stack) > 0 { + n := len(stack) // 记录当前层节点个数 + for i := 0; i < n; i++ { + node := stack[0] // 依次弹出节点 + stack = stack[1:] + if i == n - 1 { // 如果是这层最右的节点,next指向nil + node.Next = nil + } else { + node.Next = stack[0] // 如果不是最右的节点,next指向右边的节点 + } + if node.Left != nil { // 如果存在左子节点,放入栈中 + stack = append(stack, node.Left) + } + if node.Right != nil { // 如果存在右子节点,放入栈中 + stack = append(stack, node.Right) + } + } + } + return root +} +``` +```go +// 常量级额外空间,使用next +func connect(root *Node) *Node { + if root == nil { + return root + } + for cur := root; cur.Left != nil; cur = cur.Left { // 遍历每层最左边的节点 + for node := cur; node != nil; node = node.Next { // 当前层从左到右遍历 + node.Left.Next = node.Right // 左子节点next指向右子节点 + if node.Next != nil { //如果node next有值,右子节点指向next节点的左子节点 + node.Right.Next = node.Next.Left + } + + } + } + return root +} ``` ## JavaScript