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



 

你可能感兴趣的:(leetcode)