426 Convert Binary Search Tree to Sorted Doubly Linked List

Python

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, left, right):
        self.val = val
        self.left = left
        self.right = right
"""
class Solution(object):
    def helper(self, root):
        head, tail = root, root
        if root.left:
            left_head, left_tail = self.helper(root.left)
            left_tail.right = root
            root.left = left_tail
            head = left_head

        if root.right:
            right_head, right_tail = self.helper(root.right)
            right_head.left = root
            root.right = right_head
            tail = right_tail

        head.left = tail
        tail.right = head
        return head, tail    

    def treeToDoublyList(self, root):
        """
        :type root: Node
        :rtype: Node
        """
        if not root:
            return root

        head, tail = self.helper(root)
        return head

results matching ""

    No results matching ""