[Leetcode] 99. Recover Binary Search Tree

这篇博客介绍了如何利用Morris算法和中序遍历来修复二叉搜索树中两个节点值错误的问题。方法1通过Morris遍历找到错误节点并交换值,时间复杂度和空间复杂度均为O(n)。方法2通过中序遍历列表找到错误节点并交换,同样保持O(n)的时间复杂度。方法3在递归过程中记录错误节点,交换节点值。所有方法均不使用额外的数据结构,仅修改原树。
摘要由CSDN通过智能技术生成

最优解:Morris 算法

Morris 算法介绍及代码: https://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/

Use Morris in-order traverse, keep the two wrong nodes and switch their values after the traverse.

Time complexity: O(n)
Space complexity: O(1), the benefit of Morris algorithm

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right


class Solution:
    def recoverTree(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        x = y = pred = None
        while root:
            if not root.left:
                if pred and root.val < pred.val:
                    y = root
                    if not x:
                        x = pred
                pred = root
                root = root.right
            else:
                predecessor = root.left
                while predecessor.right and predecessor.right != root:
                    predecessor = predecessor.right
                if not predecessor.right:
                    predecessor.right = root
                    root = root.left
                else:
                    if pred and root.val < pred.val:
                        y = root
                        if not x:
                            x = pred
                    pred = root
                    predecessor.right = None
                    root = root.right
                    
        x.val, y.val = y.val, x.val

方法2: By in order traverse list

Time complexity: O(n)
Space complexity: O(n)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def recoverTree(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        in_order = []
        self.dfs(root, in_order)
        node1, node2 = None, None
        print(in_order)
        for i in range(len(in_order) - 1):
            if in_order[i].val > in_order[i + 1].val:
                node1 = in_order[i]
                break
        for i in range(len(in_order) - 1, 0, -1):
            if in_order[i].val < in_order[i - 1].val:
                node2 = in_order[i]
                break
        tmp = node1.val
        node1.val = node2.val
        node2.val = tmp
    
    def dfs(self, root, in_order):
        if root is None:
            return
        self.dfs(root.left, in_order)
        in_order.append(root)
        self.dfs(root.right, in_order)

方法3: keep wrong nodes during recursion

time complexity: O(n)
space complexity: O(n) stack space
** dfs时先左边,最后右边,中间是对当前情况的处理和判断。注意判断当前node的合法性的位置,在prev赋值为当前node之前

class Solution:
    def recoverTree(self, root: TreeNode) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        self.prev = None
        self.count = 0
        self.dfs(root)
        tmp = self.node1.val
        self.node1.val = self.node2.val
        self.node2.val = tmp
    
    def dfs(self, root):
        if root is None:
            return
        self.dfs(root.left)
        if self.prev and root.val < self.prev.val:
            if self.count == 0:
                self.node1 = self.prev
                self.node2 = root
                self.count += 1
            elif self.count == 1:
                self.node2 = root
                self.count += 1
                return
        self.prev = root
        self.dfs(root.right)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值