Populating Next Right Pointers in Each Node II
Given a binary tree
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Example 1:

Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range
[0, 6000]. -100 <= Node.val <= 100
Follow-up:
- You may only use constant extra space.
- The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
"""
# 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: 'Node') -> 'Node':
if root is None :
return root
self.postorder(node=root, level=0, dct={})
return root
def postorder(self, node, level:int, dct:dict) :
node.next = None
if node.left :
self.postorder(node.left, level+1, dct)
if node.right :
self.postorder(node.right, level+1, dct)
if level in dct.keys() :
dct[level].next = node
dct[level] = node
이 문제는 봐도봐도 이해가 참 어렵다. postorder를 활용하는 문제이다. postorder는 가장 아래에 있는 리프노드를 순차로 방문하면서 위로 올라가는 구조이다. 그래서 case1 의 방문 순서는 4, 5, 2, 7, 3, 1 순이 될 것이고, 정답은 4,5,7/2,3/1 이 될 것이다. 그래서 정답에도 이런 식으로 표현되었다.
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
방문 순서를 기반으로 보면,
4 : level = 2 에 존재하는 노드로 dct[2] = None 이기 때문에 dct = {2:4}, 그리고 정답에 node=[4]
5 : level = 2, dct[2] = 4가 존재하므로 4.next = 5가 되고 dct = {2:5} 로 갱신. node = [4 -> 5]
2 : level = 1, dct[1] = None이므로 dct = {2:5, 1:2}. node = [4 -> 5, 2]
7 : level = 2, dct[2] = 5이며 4->5 로 정답에 인풋 되어 있기 때문에 dct = {2:7, 1:2}. node = [4 -> 5 -> 7, 2]
3 : level = 1, dct[1] = 2이며 dct = {2:7, 1:3}으로 갱신. node = [4 -> 5 -> 7, 2 -> 3]
1 : level = 0, dct[0] = None이다. dct = {2:7, 1:3, 0:1}로 갱신되며, node = [4 -> 5 -> 7, 2 -> 3, 1] 로 갱신 후 return 되게 된다.
이를 정리하면 root = [1, 2 -> 3, 4 -> 5 -> 7] 로 정리할 수 있으며 정답과 동일한 것을 알 수 있다.
열심히 연습하자.
'알고리즘 스터디' 카테고리의 다른 글
| [Leetcode/파이썬] 167. Two Sum II - Input Array Is Sorted (0) | 2025.11.21 |
|---|---|
| [백준/파이썬] 19238. 스타트 택시 (0) | 2025.11.12 |
| [Leetcode/파이썬] 120. Triangle (0) | 2025.11.09 |
| [Leetcode/파이썬] 74. Search a 2D Matrix (0) | 2025.11.09 |
| [Leetcode/파이썬] 46. Permutations (0) | 2025.10.31 |