Flatten Binary Tree to Linked List – Python 3 (Week 14 – 16)

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: a TreeNode, the root of the binary tree
    @return: nothing
    """
    def flatten(self, root):
        # write your code here
        self.helper(root)
        
    def helper(self, root):
        if not root:
            return root
        
        left_last = self.helper(root.left)
        right_last = self.helper(root.right)
        
        if left_last:
            left_last.right = root.right
            root.right = root.left
            root.left = None
        
        return right_last or left_last or root

Leave a comment

Design a site like this with WordPress.com
Get started