Recovery Binary Search Tree Leetcode Python

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

题目要求找到BST中被swap的两个节点并把它们复原,这里考虑到是BST 我们可以用Inorder traverse,如果没有被调换之前的所有节点值满足序号从小到大 数组依次增大。 如果被调换,假如原来序列为1 2 3 4 5 6 7,这里假设1和7被调换,最后为7 2 3 4 5 6 1 第一个被调换的数是比后面的数大 7>2 第二个被调换的是1 比前面的小 6>1,依次取出 7 和1 将他们换回去,可以得到答案。

This problem can be solved by using inorder traverse, in general BST if we inorder traverse the tree, we can get an array with increasing order. However, if two of the nodes are swapped, lets assume the original order is 1 2 3 4 5 6 7, we swap 1 and 7 here. The result will become 7 2 3 4 5 6 1, the first swapped element is the node greater than its post node, which is 7>2. The second node will be the node smaller than its pre node 6>1.

Now we need to swap these two nodes, we get the answer.


# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return a tree node
    def inorder(self,root):
        if root:
            self.inorder(root.left)
            if self.prev and self.prev.val>root.val:
                self.n2=root
                if self.n1==None:
                    self.n1=self.prev
            self.prev=root
            self.inorder(root.right)
    def recoverTree(self, root):
        self.n1,self.n2=None,None
        self.prev=None
        self.inorder(root)
        self.n1.val,self.n2.val=self.n2.val,self.n1.val
        return root



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值