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

二叉搜索树与双向链表

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 PreNode(self, root : TreeNode):
        this = root
        if not this:
            return None
        if this.left:
            this = this.left
            while this.right:
                this = this.right
            root.left = this
            this.right = root
    def RearNode(self, root : TreeNode):
        this = root
        if not this:
            return None
        if this.right:
            this = this.right
            while this.left:
                this = this.left
            root.right = this
            this.left = root
    def LDR(self, this : TreeNode):
        if this:
            self.LDR(this.left)
            # 遍历完左孩子后,左指针解放,于是可以将左指针指向前驱
            self.PreNode(this)

            self.LDR(this.right)
            # 遍历完右孩子后,右指针解放,于是可以将右指针指向后继
            self.RearNode(this)

    def Convert(self , pRootOfTree ):
        # write code here
        this = pRootOfTree
        if not this:
            return None
        # 找到最小节点,作为头节点
        while this.left:
            this = this.left
        head = this
        self.LDR(pRootOfTree)
        return head

全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务