99. Recover Binary Search Tree刷题笔记

Morris遍历可以在空间复杂度为O(1),时间复杂度为O(n)

二叉搜索树
前驱结点:节点val值小于该节点val值并且值最大的节点,A节点的前驱是B,就是B恰好比A小
后继节点:节点val值大于该节点val值并且值最小的节点

记作当前节点为cur。

如果cur无左孩子,cur向右移动(cur=cur.right)
如果cur有左孩子,找到cur左子树上最右的节点,记为mostright
如果mostright的right指针指向空,让其指向cur,cur向左移动(cur=cur.left)
如果mostright的right指针指向cur,让其指向空,cur向右移动(cur=cur.right)
Morris遍历的原理
可以代入到这个图里看看

最后参照的是这个题解,代码没搞懂

class Solution:
  def recoverTree(self, root: Optional[TreeNode]) -> None:
    pred = None
    x = None  # 1st wrong node
    y = None  # 2nd wrong node

    def findPredecessor(root: Optional[TreeNode]) -> Optional[TreeNode]:
      pred = root.left
      while pred.right and pred.right != root:
        pred = pred.right
      return pred

    while root:
      if root.left:
        morrisPred = findPredecessor(root)
        if morrisPred.right:  # already connected before
          # start the main logic
          if pred and root.val < pred.val:
            y = root
            if not x:
              x = pred
          pred = root
          # end of the main logic
          morrisPred.right = None  # break the connection
          root = root.right
        else:
          morrisPred.right = root  # connect it!
          root = root.left
      else:
        # start the main logic
        if pred and root.val < pred.val:
          y = root
          if not x:
            x = pred
        pred = root
        # end of the main logic
        root = root.right


    x.val,y.val = y.val,x.val

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值