Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 7. 27. 23:45

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

 

Flatten Binary Tree to Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이번에도 트리 문제 ㅎㅎㅎ

class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
        def to_right(root):
            if root.right:
                return to_right(root.right)
            return root
        
        if root:
            next_right = None
            right_most = None
            
        while root:
            if root.left:
                right_most = to_right(root.left)
                next_right = root.right
                root.right = root.left
                root.left = None
                right_most.right = next_right
            
            root = root.right
반응형