Apr 19, 2018

[LC] bst to double linked list

bst <-> double linked list.
straight.
class Solution(object):
    def bst_llst(self, root):

        def dfs(root):
            """
            :param root: Node
            :ret: (min, max)
                    9

                 6        14

              3    8|  12
                 /
                7

            """

            if not root:
                return

            lmin = lmax = rmin = rmax = None

            if root.left:
                lmin, lmax = dfs(root.left)
                lmax.right = root
                root.left = lmax

            if root.right:
                rmin, rmax = dfs(root.right)
                root.right = rmin
                rmin.left = root

            if not lmin:
                lmin = root
            if not rmax:
                rmax = root

            return lmin, rmax

        mmin, mmax = dfs(root)

        mmin.left = mmax
        mmax.right = mmin
        return mmin

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.