Skip to content

Latest commit

 

History

History

114-FlattenBinaryTreetoLinkedList

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Flatten Binary Tree to Linked List

Problem can be found in here!

# 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

def flatten(self, root: Optional[TreeNode]) -> None: if not root: return None

node = root
while node:
    if node.left:
        rightmost = node.left
        while rightmost.right:
            rightmost = rightmost.right

        rightmost.right = node.right
        node.right = node.left
        node.left = None

    node = node.right

Time Complexity: O(n), Space Complexity: O(n)