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?
主要思路:
使用树的递归中序遍历,当出现当前值比前一个小的时候,就存在不合法的节点。用pre存中序遍历时当前节点的前一个节点,方便值的大小对比。用p,q记录两个不合法序列的位置,p指向较小的值,q指向较大的值。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *p, *q, *pre;
void recoverTree(TreeNode *root) {
p = q = pre = nullptr;
inorder(root);
swap(p->val, q->val);
}
void inorder(TreeNode *root)
{
if(root == nullptr) return;
if(root->left) inorder(root->left);
if(pre && pre->val > root->val)
{
if(p == nullptr)
p = pre;
q = root;
}
pre = root;
if(root->right) inorder(root->right);
}
};
参考:http://www.cnblogs.com/tgkx1054/archive/2013/05/24/3096830.html