Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Example 1:
Input: [1,3,null,null,2]
1
/
3
\
2
Output: [3,1,null,null,2]
3
/
1
\
2
Example 2:
Input: [3,1,4,null,null,2]
3
/ \
1 4
/
2
Output: [2,1,4,null,null,3]
2
/ \
1 4
/
3
Follow up:
- A solution using O(n) space is pretty straight forward.
- Could you devise a constant space solution?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
这道题一开始是我想复杂了,我以为是一颗置乱树的重排序问题,但这里只是两个树的错位,就简单很多,只要找到错位的两个数就行了。分别用指针指向这两个数,再将其交换就行了。
我之前一直在烦恼如何用指针表示二叉树中两个相邻的节点,原因在于还不真正懂得递归,在这个inordertra函数里先遍历左子树便是会一直深入到整棵树最左边的节点,那个节点就是整棵树中最小的节点,pre便从最小的节点开始,当pre是空的时候,pre与_root指向同一个节点。然后深入右子树最小的节点,然后再跳到_root节点。这就可以保证pre和_root节点是相邻的两个节点。这里最重要的应该是pre指针对于inordertra函数来说是一个外部变量,而_root指针是一个内部变量,随着递归不断改变;
*/
class Solution {
public:
void recoverTree(TreeNode* root)
{
inordertra(root);
swap(first->val,second->val);
}
private:
TreeNode* pre = NULL;
TreeNode* first = NULL;
TreeNode* second = NULL;
void inordertra(TreeNode* _root)
{
if(!_root) return;
inordertra(_root->left);
if(pre && pre->val > _root->val)
{
if(!first) first = pre;
second = _root;
}
pre = _root;
inordertra(_root->right);
}
};
补充 : 这道题只是两个乱序的元素,所以最多只会出现① > ② > ③ 或者 ① > ②这样的情况,才能通过互换两个元素得到正确的二叉搜索树,而对于① > ② > ③ 这样的情况,first_element指针不改变 , 但是second_element的指针需要一直改变;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode *pre_element = NULL , *first_element = NULL , *second_element = NULL ;
public:
void recoverTree(TreeNode* root)
{
inOrder(root) ;
swap(first_element->val , second_element->val) ;
}
void inOrder(TreeNode* root)
{
if(!root) return ;
inOrder(root->left);
if(pre_element && pre_element->val > root->val)
{
if(!first_element) first_element = pre_element ;
second_element = root ;
cout<<"in"<<"pre_element.val : "<<pre_element->val<<endl;
}
if(root) pre_element = root ;
cout<<"pre_element.val : "<<pre_element->val<<endl;
inOrder(root->right) ;
}
};