ONE is all.

# Problem Statement

(Source) Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

# Analysis

Think of the in-order traversal sequence of a binary search tree. It is an increasing sequence. If two elements of the original binary search tree are swapped, then the new in-order traversal sequence would not be in ascending order anymore, but it must fit into one of the following two cases:
(1) There exists only one pair of elements (seq[i], seq[i + 1]) in the new sequence such that seq[i] > seq[i + 1].
(2) There exists two pairs of elements (seq[i], seq[i + 1]), (seq[j], seq[j + 1]) in the new sequence such that seq[i] > seq[i + 1] && seq[j] > seq[j + 1].

Therefore, the idea to solve the problem is to find the first node corresponding to the first element of the first pair, and the last node corresponding to the last element of the last pair, no matter which case the new sequence fits into, and swap them.

Solution below uses an recursive implementation below, which runs in:
- Time complexity: O(n), where n is the total number of the binary search tree.
- Space complexity: O(1).

# Solution

# 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.
"""
swapped_nodes = []
prev = [None]

def inorder(p, prev, swapped_nodes):
if p.left:
inorder(p.left, prev, swapped_nodes)

if prev[0] and prev[0].val > p.val:
if len(swapped_nodes) == 0:
swapped_nodes.extend([prev[0], p])
else:
swapped_nodes[1] = p
prev[0] = p

if p.right:
inorder(p.right, prev, swapped_nodes)

inorder(root, prev, swapped_nodes)

swapped_nodes[0].val, swapped_nodes[1].val = swapped_nodes[1].val, swapped_nodes[0].val

#### LeetCode 99:Recover Binary Search Tree

2015-12-28 15:37:36

#### LeetCode99—Recover Binary Search Tree

2016-03-19 22:12:41

#### leetcode 99 Recover Binary Search Tree (python)

2016-07-25 23:37:11

#### 【LeetCode】Recover Binary Search Tree 解题报告

2015-03-21 11:58:37

#### leetcode：Recover Binary Search Tree （修正二叉查找树错误节点，不改变结构）【面试算法题】

2013-10-19 11:13:29

#### [leetcode] 99. Recover Binary Search Tree 解题报告

2016-01-14 13:27:39

#### Recover Binary Search Tree -- LeetCode

2014-04-27 03:09:51

#### 【LeetCode】669 Trim a Binary Search Tree

2017-09-08 15:53:21

#### leetcode 173: Binary Search Tree Iterator

2015-01-02 12:44:56

#### Convert Sorted List to Binary Search Tree -- LeetCode

2014-04-17 07:57:02

## 不良信息举报

LeetCode #99: Recover Binary Search Tree