恢复二叉搜索树

作者: 而立之年的技术控 | 来源:发表于2019-12-19 21:53 被阅读0次
    微信图片_20191219215206.jpg
    class Solution:
        def __init__(self):
            self.firstNode = None
            self.secondNode = None
            self.preNode = TreeNode(float('-inf'))
        def recoverTree(self, root: TreeNode) -> None:
            """
            Do not return anything, modify root in-place instead.
            """
    
            def order(root):
                if not root:
                    return
                order(root.left)
                if self.firstNode == None and self.preNode.val >= root.val:
                    self.firstNode = self.preNode
                if self.firstNode and self.preNode.val >= root.val:
                    self.secondNode = root
                self.preNode = root
                order(root.right)
            order(root)
            
            if self.firstNode and self.secondNode:
                self.firstNode.val, self.secondNode.val = self.secondNode.val, self.firstNode.val
    

    相关文章

      网友评论

        本文标题:恢复二叉搜索树

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