LeetCode-Recover Binary Search Tree-恢复二叉排序树
https://oj.leetcode.com/problems/recover-binary-search-tree/
思路是首先按中序把节点序列打到数组里。然后扫描数组看是哪两个数需要交换。考虑ai和aj是需要交换的两个值,其中i<j。则现在应该有a[i+1]<a[i],a[j]<a[j-1]。所以只需要找到两个小于前面数的数字即可。
一个边界情况是,实际需要交换的元素就是a[i]和a[i+1]。这种情况应该只能找到一个不合法的i,此时另一个需要交换的设置为i即可。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int n,m;
vector <TreeNode *> v;
void InOrder(TreeNode *root){
if (root==NULL) return;
InOrder(root->left);
v.push_back(root);
InOrder(root->right);
}
void recoverTree(TreeNode *root) {
InOrder(root);
n=v.size();
if (n<=1) return;
int ps[2];
int count=0;
for (int i=1;i<n;i++){
if (v[i]->val<v[i-1]->val) {
ps[count++]=i;
}
}
if (count<1) return;
if (count<2) ps[count++]=ps[0];
TreeNode *l=v[ps[0]-1];
TreeNode *r=v[ps[1]];
swap(l->val,r->val);
}
};
浙公网安备 33010602011771号