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

二叉搜索树与双向链表

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 Convert_row(self, pRootOfTree:TreeNode):
        if not pRootOfTree:
            return None, None
    # 递归拿到子串的两头,如果没有就返回None
        if pRootOfTree.left:
            lleft, lrignt = self.Convert_row(pRootOfTree.left)
        else:
            lleft, lrignt = None, None
        if pRootOfTree.right:
            rleft, rright = self.Convert_row(pRootOfTree.right)
        else:
            rleft, rright = None, None
        
    # 左,自身,右,接上
        pRootOfTree.left = lrignt
        pRootOfTree.right = rleft
        if lrignt:
            lrignt.right = pRootOfTree
        if rleft:
            rleft.left = pRootOfTree

    # 如果没有左头,那自身就是左头,右边同理
        if lleft == None:
            left = pRootOfTree
        else:
            left = lleft
        if rright == None:
            right = pRootOfTree
        else:
            right = rright

        return left,right

    def Convert(self,pRootOfTree:TreeNode):
        left, right= self.Convert_row(pRootOfTree)
        return left

全部评论

相关推荐

10-30 10:16
南京大学 Java
永远的鹅孝子:给南大✌️跪了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务