首页 > 编程语言 > 详细

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

时间:2016-03-07 18:36:32      阅读:240      评论:0      收藏:0      [点我收藏+]

题目来源:

  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

原文:http://www.cnblogs.com/chruny/p/5251314.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!