二叉搜索树与双向链表

递归

class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        self.pre = None
        self.pHead = None
        self.digui(pRootOfTree)
        return self.pHead
    
    def digui(self, pRootOfTree):
        if not pRootOfTree:
            return None
        self.digui(pRootOfTree.left)
        if not self.pre:
            self.pHead = pRootOfTree
            self.pre = pRootOfTree
        else:
            self.pre.right = pRootOfTree
            pRootOfTree.left = self.pre
            self.pre = pRootOfTree
        self.digui(pRootOfTree.right)

非递归

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class Solution:
    def Convert(self, pRootOfTree):
        # write code here
        pre = None
        stack = []
        pHead = None
        while stack or pRootOfTree:
            if pRootOfTree:
                stack.append(pRootOfTree)
                pRootOfTree = pRootOfTree.left
            else:
                pRootOfTree = stack.pop()
                if pre:
                    pre.right = pRootOfTree
                    pRootOfTree.left = pre
                else:
                    pHead = pRootOfTree
                pre = pRootOfTree
                pRootOfTree = pRootOfTree.right
        return pHead

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