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

Posted Ry_Chen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode]题解(python):099-Recover Binary Search Tree相关的知识,希望对你有一定的参考价值。

题目来源:

  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]
        
View Code

 

以上是关于[LeetCode]题解(python):099-Recover Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode]题解(python):100 Same Tree

[LeetCode]题解(python):112 Path Sum

[LeetCode]题解(python):133-Clone Graph

問題の解決策 ARC099 D - Snuke Numbers

[LeetCode]题解(python):101-Symmetric Tree

[LeetCode]题解(python):101 Symmetric tree