mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1129 from leeeeeeewii/116
增加 0116.填充每个节点的下一个右侧节点指针.md Go版本
This commit is contained in:
@ -211,9 +211,52 @@ class Solution:
|
|||||||
return root
|
return root
|
||||||
```
|
```
|
||||||
## Go
|
## Go
|
||||||
|
|
||||||
```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
|
## JavaScript
|
||||||
|
Reference in New Issue
Block a user