99. 恢复二叉搜索树
原始题目链接:https://leetcode-cn.com/problems/recover-binary-search-tree/
给你二叉搜索树的根节点 root ,该树中的两个节点被错误地交换。请在不改变其结构的情况下,恢复这棵树。
进阶:使用 O(n) 空间复杂度的解法很容易实现。你能想出一个只使用常数空间的解决方案吗?
解题思路:
1、先中序遍历,得到包含被错误交换的节点列表。
2、将中序遍历得到的列表进行排序。
3、查找两个列表不一样的值,交换即可。
代码实现:
# 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.
"""
# 中序遍历二叉搜索树,应该得到一个有序的序列
# 使用匿名函数lambda,可以简化代码
# 返回的是中序遍历后的节点列表
tree = lambda x : [] if not x else tree(x.left) + [x] + tree(x.right)
# 调用上面的匿名函数
unsorted_nodes_list = tree(root)
# 再对上面的节点列表进行排序,按照节点的val值排序
sorted_nodes_list = sorted(unsorted_nodes_list, key = lambda x: x.val)
# 查找没排序的节点列表的和排序节点列表的不一样的节点值
# 找到后,交换即可
node_a, node_b = [unsorted_nodes_list[i] for i in range(len(unsorted_nodes_list)) if unsorted_nodes_list[i] != sorted_nodes_list[i]]
node_a.val, node_b.val = node_b.val, node_a.val
参考文献:
https://leetcode-cn.com/problems/recover-binary-search-tree/solution/python3-zhong-xu-bian-li-wu-xing-dai-ma-by-ting-ti/