JZ26:二叉搜索树与双向链表

题目描述:

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。

解法:

二叉搜索树的中序遍历(左-中-右)是递增序列。先中序遍历,然后两两双向链接即可。

代码:

class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        if not pRootOfTree:
            return None
        elif not pRootOfTree.left and not pRootOfTree.right:
            return pRootOfTree
        stack = []
        inorder = []
        while stack or pRootOfTree:
            while pRootOfTree:
                stack.append(pRootOfTree)
                pRootOfTree = pRootOfTree.left
            pRootOfTree = stack.pop()
            inorder.append(pRootOfTree)
            pRootOfTree = pRootOfTree.right
        inorder[0].left = None
        inorder[0].right = inorder[1]
        for i in range(1, len(inorder)-1):
            inorder[i].left = inorder[i-1]
            inorder[i].right = inorder[i+1]
        inorder[len(inorder)-1].left = inorder[len(inorder)-2]
        inorder[len(inorder)-1].right = None
        return inorder[0]

你可能感兴趣的:(JZ26:二叉搜索树与双向链表)