[Leetcode] 114. Flatten Binary Tree to Linked List

서해빈·2021년 4월 3일
0

코딩테스트

목록 보기
38/65

문제 바로가기

# 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: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        # return a leaf node of a flatten subtree
        def DFS(node: TreeNode) -> TreeNode:
            if node is None:
                return

            leftLeaf = DFS(node.left)
            rightLeaf = DFS(node.right)
            
            if leftLeaf is not None:
                node.right, leftLeaf.right = node.left, node.right
                node.left = None
            
            return rightLeaf or leftLeaf or node
        
        DFS(root)

0개의 댓글