美文网首页
二叉搜索树与双向链表

二叉搜索树与双向链表

作者: reeuq | 来源:发表于2018-08-02 11:36 被阅读0次

    递归

    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
    

    相关文章

      网友评论

          本文标题:二叉搜索树与双向链表

          本文链接:https://www.haomeiwen.com/subject/vxjlpftx.html