99. Recover Binary Search Tree
题目
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?
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1
/
2 3
/
4
5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".
解析
class Solution_99 {
public:
void recoverTree(TreeNode* root) {
TreeNode* first = NULL, *second = NULL, *parenet = NULL;
TreeNode*cur, *pre; //中序遍历
cur = root;
while (cur)
{
if (cur->left==NULL)
{
if (parenet&&parenet->val>cur->val)
{
if (!first)
{
first = parenet;
}
second = cur;
}
parenet = cur;
cur = cur->right;
}
else
{
pre = cur->left; //找到左子树的最右节点
while (pre->right&&pre->right!=cur)
{
pre = pre->right;
}
if (!pre->right)
{
pre->right = cur;
cur = cur->left;
}
else
{
pre->right = NULL; //恢复树结构
if (parenet&&parenet->val > cur->val)
{
if (!first)
{
first = parenet;
}
second = cur;
}
parenet = cur;
cur = cur->right;
}
}
}
if (first&&second)
{
swap(first->val, second->val);
}
}
};
题目来源