恢复二叉搜索树

给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树。

示例 1:

复制代码
输入:root = [1,3,null,null,2]
输出:[3,1,null,null,2]
解释:3 不能是 1 的左孩子,因为 3 > 1 。交换 1 和 3 使二叉搜索树有效。

示例 2:

复制代码
输入:root = [3,1,4,null,null,2]
输出:[2,1,4,null,null,3]
解释:2 不能在 3 的右子树中,因为 2 < 3 。交换 2 和 3 使二叉搜索树有效。

思路:

二叉搜索树按中序遍历是一个递增的序列,我们只需找到两个错误的节点即可。

在遍历过程中,不满足递增时,就意味着出现了要交换的点(这种情况共两次,分别对应两个错误的节点)

python 复制代码
if root.val < self.pre.val:
      self.index2 = root
      if self.index1 == None:
         self.index1 = self.pre

这个交换很巧妙,可以实际演示一遍,index1和index2正好可以记录下两个错误的节点。

代码如下:

python 复制代码
# Definition for a binary tree node.
from typing import Optional


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: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """

        def inorder(root):
            if not root:
                return
            inorder(root.left)
            if root.val < self.pre.val:
                self.index2 = root
                if self.index1 == None:
                    self.index1 = self.pre
            self.pre = root
            inorder(root.right)

        self.pre = TreeNode(-float('inf'))
        self.index1 = None
        self.index2 = None
        inorder(root)
        self.index1.val, self.index2.val = self.index2.val, self.index1.val
相关推荐
高级程序源21 分钟前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
WeiXin_DZbishe33 分钟前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
KIDULT°37 分钟前
MySQL系列 (1):数据库原理
运维·数据库·mysql·云计算
kimnoic1 小时前
Python数据库学习心得:SQLite、MySQL、PostgreSQL优缺点
开发语言·python
我不是程序员三三1 小时前
透明加密软件偶发解密异常排错实录:文件时能打开时乱码
数据库·域智盾
snhna1 小时前
向量数据库深度实战:从 HNSW 到 pgvector、Milvus 选型与 RAG 落地
数据库·人工智能·python·postgresql·milvus
Nil2081 小时前
leetcode 763划分字母区间
算法·leetcode·职场和发展
不会就选b1 小时前
算法日常・每日刷题--<动态规划>20
算法·leetcode·动态规划
天行健,君子而铎1 小时前
数据分类分级的范式转换:从规则匹配到场景化高准确率一键部署
网络·数据库·安全
牛战士coding2 小时前
MySQL 读写分离完整链路:主从复制、多数据源与 @DS 路由
数据库·mysql