https://youtu.be/U4hFQCa1Cq0?si=qOfcXWT90Uo5RjvE
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
cur, nxt = root, root.left if root else None
while cur and nxt: # cur is not null, and nxt is not null
cur.left.next = cur.right
if cur.next: # cur.next is not null
cur.right.next = cur.next.left
cur = cur.next # 오른쪽으로 넘어갔는데,
if not cur: # null 이라는 말은 오른쪽 끝이라는 것이니, 다음 레벨로 하나씩 옮기기.
cur = nxt
nxt = cur.left
return root
'LeetCode > 주제별 보충' 카테고리의 다른 글
Tree: 543. Diameter of Binary Tree ★ (0) | 2025.01.16 |
---|---|
BST Sets and Maps ★★ (0) | 2025.01.16 |
BFS: Binary Tree Right Side View (0) | 2025.01.16 |
BFS: 102. Binary Tree Level Order Traversal (0) | 2025.01.16 |
DFS: 94. Binary Tree Inorder Traversal (0) | 2025.01.15 |