작심삼일

[LeetCode] 114 | Flatten Binary Tree to Linked List | Python 본문

스터디/코테

[LeetCode] 114 | Flatten Binary Tree to Linked List | Python

yun_s 2022. 7. 27. 10:12
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
반응형
Comments