【ATT】Recover Binary Search Tree
Q: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?
A: 如果交换了,inorder seq中的逆序对可能是1对(父子节点交换),或者2对。
void recoverTree(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. TreeNode* n1 = NULL,*n2 = NULL,*prev = NULL; getErrorNodes(root,n1,n2,prev); if(n1&&n2) { int tmp = n1->val; n1->val = n2->val; n2->val = tmp; } } void getErrorNodes(TreeNode* root,TreeNode* &n1,TreeNode* &n2,TreeNode*& prev) { if(!root) return; getErrorNodes(root->left,n1,n2,prev); //prev是inoder seq的前一个节点 if(prev&&prev->val>root->val) //发现逆序对。 { n2 = root; if(!n1) n1 = prev; } prev = root; getErrorNodes(root->right,n1,n2,prev); }
如果要求O(1)的空间复杂度,把inorder recursive改为递归做,即可。