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

二叉搜索树与双向链表

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

全部评论

相关推荐

当年还在美团那个倒霉的 Peppr 团队工作时,我一直有个疑问:这群人每天到底在自嗨什么。每次开会一堆人围着一堆“看起来很高级”的文档转,模板统一、名词复杂、页数感人,每一页都在暗示一件事:“你不懂,是因为你不专业。”但现实是——代码照样写在 💩 山上,该出问题还是会出问题,这真的很逗,系统一出问题,文档的唯一作用就是证明:“我们当初确实认真写过文档。”所以本质区别到底是什么?是代码质量提升了,还是大家在精神层面完成了一次“工程师 cosplay”?有句话说得好潮水退去才知道谁在裸泳。还记得当时的马哥、明哥(图 1 左)最爱反复强调一句话:“所有场景一定要想到。”、“这个场景为什么没考虑到?”不过他们这些话我是真的听进去了。不然我也不会在一年多前就说:这个项目活不过两年。顺带一提,那段时间还有个固定节目。每次下楼,总能听见我明哥在吐槽不同的人。我从他身后绕过去,经常能听到他一边抽烟一边说:“xx 这小子太坑了,回头我一定要跟马哥说说。”于是深谙人情世故但真不会抽烟的我也会从口袋掏出一支低尼古丁含量的烟给自己点上,假意自己什么都没听到什么都不知道,只是来抽烟的。后来我才明白,这可能也是团队文化的一部分:问题永远在别人身上,而我们,永远在复盘里😂。
秋招白月光
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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