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指针,记录当前节点中序遍历时的前节点,如果当前节点大于pre节点的值,说明需要调整次序。
有一个技巧是如果遍历整个序列过程中只出现了一次次序错误,说明就是这两个相邻节点需要被交换。如果出现了两次次序错误,那就需要交换这两个节点。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode *mis1 = NULL, *mis2 = NULL, *pre = NULL;
public:
void recoverTree(TreeNode *root){
if( root == NULL)
return;
findMisNode( root);
swap( mis1->val, mis2->val);
}
void findMisNode( TreeNode *root){
if( root == NULL)
return;
if( root->left)
findMisNode( root->left);
if( pre != NULL && pre->val > root->val){
if( mis1 == NULL){
mis1 = pre;
mis2 = root;
}
else
mis2 = root;
}
pre = root;
findMisNode( root->right);
}
};