Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 281b3f7

Browse files
🐱(tree): 116. 填充每个节点的下一个右侧节点指针
1 parent d411d17 commit 281b3f7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

‎docs/data-structure/tree/recursion/README.md‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,48 @@ func hasPathSum(root *TreeNode, sum int) bool {
481481

482482
<!-- tabs:end -->
483483

484+
## 116. 填充每个节点的下一个右侧节点指针
485+
486+
[原题链接](https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/)
487+
488+
### 解一:递归
489+
490+
- `root.left.next = root.right`
491+
- 利用已经处理好的 `next` 指针:`root.right.next = root.next.left`
492+
493+
<!-- tabs:start -->
494+
495+
#### **Python**
496+
497+
```python
498+
"""
499+
# Definition for a Node.
500+
class Node:
501+
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
502+
self.val = val
503+
self.left = left
504+
self.right = right
505+
self.next = next
506+
"""
507+
class Solution:
508+
def connect(self, root: 'Node') -> 'Node':
509+
self.handler(root)
510+
return root
511+
512+
def handler(self, root):
513+
if root is None or root.left is None:
514+
return None
515+
root.left.next = root.right
516+
if root.next is not None:
517+
root.right.next = root.next.left
518+
# 关联节点
519+
self.connect(root.left)
520+
# 关联右节点
521+
self.connect(root.right)
522+
```
523+
524+
<!-- tabs:end -->
525+
484526
## 226. 翻转二叉树
485527

486528
[原题链接](https://leetcode-cn.com/problems/invert-binary-tree/description/)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /