题目:
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
代码:
/**
* 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 {
public:
bool Inorder(TreeNode* root,TreeNode*& last) {
bool flag1 = true,flag2=true,flag3=true;
if (root) {
flag1=Inorder(root->left, last);
if (last&&last->val > root->val) {
int temp = last->val;
last->val = root->val;
root->val = temp;
flag2 = false;
}
last = root;
flag3=Inorder(root->right, last);
}
return flag1&&flag2&&flag3;
}
void recoverTree(TreeNode* root) {
bool flag = false;
while(!flag){
TreeNode* last = NULL;
flag = Inorder(root, last);
}
}
};
想法:
要试着从逻辑上讲通。