반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 114 | Flatten Binary Tree to Linked List | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
문제
Given the root of a binary tree, flatten the tree into a "linked list":
- The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
- The "linked list" should be in the same order as a pre-order traversal of the binary tree.
조건
- The number of nodes in the tree is in the range [0, 2000].
- -100 <= Node.val <= 100
내 풀이
Binary Tree를 전부 다 오른쪽으로 모는 문제다.
root와 제일 먼 노드부터 하나씩 오른쪽으로 옮긴다.
코드
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def traverse(root):
if not root:
return
if root.left:
temp = root.left
while temp.right:
temp = temp.right
temp.right = root.right
root.right = root.left
root.left = None
traverse(root.right)
traverse(root)
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 890 | Find and Replace Pattern | Python (0) | 2022.07.29 |
---|---|
[LeetCode] 242 | Valid Anagram | Python (0) | 2022.07.28 |
[LeetCode] 236 | Lowest Common Ancestor of a Binary Tree | Python (0) | 2022.07.26 |
[LeetCode] 34 | Find First and Last Position of Element in Sorted Array | Python (0) | 2022.07.25 |
[LeetCode] 86 | Partition List | Python (0) | 2022.07.22 |
Comments