반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 116 | Populating Next Right Pointers in Each Node | Python 본문
스터디/코테
[LeetCode] 116 | Populating Next Right Pointers in Each Node | Python
yun_s 2021. 12. 29. 15:46728x90
반응형
문제 링크: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
문제
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
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.
조건
- The number of nodes in the tree is in the range [0, 212 - 1].
- -1000 <= Node.val <= 1000
내 풀이
이 두가지 생각으로 해당 문제를 풀 수 있다.
left의 next는 항상 right다.
right의 next는 root의 next의 left다.
코드
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
self.comes(root)
return root
def comes(self, root):
if not root:
return
if root.left:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
else:
root.right.next = None
self.comes(root.left)
self.comes(root.right)
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 997 | Find the Town Judge | Python (0) | 2022.01.03 |
---|---|
[LeetCode] 1015 | Smallest Integer Divisible by K | Python (0) | 2021.12.30 |
[백준] 2638번 | 치즈 | (0) | 2021.12.27 |
[LeetCode] 56 | Merge Intervals | Python (0) | 2021.12.27 |
[LeetCode] 476 | Number Complement | Python (0) | 2021.12.27 |
Comments