题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#
# 
# @param pRootOfTree TreeNode类 
# @return TreeNode类
#
class Solution:
    def getConversion(self, root):
        if root is not None:
            if root.left is not None:
                lhead,ltail = self.getConversion(root.left) #返回双向链表的头和尾结点
            else:
                lhead = None
                ltail = None
            if root.right is not None:
                rhead,rtail = self.getConversion(root.right) # 返回双向链表的头结点
            else:
                rhead = None 
                rtail = None
            root.left = ltail
            root.right = rhead

            if ltail is not None:
                ltail.right = root
            else:
                lhead = root
            if rhead is not None:
                rhead.left = root
            else:
                rtail = root

            return lhead,rtail
        else:
            return root,root


    def Convert(self , pRootOfTree ):
        # write code here
        # 深度遍历 还是需要用到递归
        if pRootOfTree is None:
            return pRootOfTree
        head,pre = self.getConversion(pRootOfTree.left) #返回双向链表的头和尾结点
        sub,tail = self.getConversion(pRootOfTree.right) # 返回双向链表的头和尾结点

        pRootOfTree.left = pre
        pRootOfTree.right = sub
        if pre is not None:
            pre.right = pRootOfTree
        else:
            head = pRootOfTree
        if sub is not None:
            sub.left = pRootOfTree
        return head

全部评论

相关推荐

11-23 15:33
已编辑
门头沟学院 Java
CUTMR:换账号试试重启推荐算法,我换账号之后回复率还不错,约莫有个20%左右的消息回复率,前几页、主动招呼的HR也开始符合我期望薪资,此前的大号从招呼、回复、前几页的岗位薪资在涨幅30%+以上 用着用着聊着聊着就变成-20%,而且我开通会员之后直接0面试
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务