[LeetCode]题解(python):099-Recover Binary Search Tree

时间:2024-10-01 20:37:14

题目来源:

  https://leetcode.com/problems/recover-binary-search-tree/


题意分析:

  二叉搜索树中有两个点错了位置,恢复这棵树。


题目思路:

  如果是没有空间复杂度限制还是比较简单。首先将树的值取出来,然后排序,将相应的位置判断是否正确。如果要特定空间复杂度就难很多。


代码(python):

  

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
ans,ansr = [],[]
def solve(root):
if root:
solve(root.left)
ans.append(root.val);ansr.append(root)
solve(root.right)
solve(root)
ans.sort()
for i in range(len(ans)):
ansr[i].val = ans[i]