mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
添加116. 填充每个节点的下一个右侧节点指针-JavaScript
This commit is contained in:
@ -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;
|
||||
};
|
||||
```
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user