LC99.恢复二叉搜索树

image.png

思路:

  • 分成三步走:1. 把二叉排序树倒进一个数组当中 2.在数组内部找到两个数字分别的位置 3.搜索二叉排序树,交换指定位置的数值
  • 把二叉树倒进数组中:中序遍历即可
  • 双指针去找各自的位置,也不难
  • 递归查找,遇到指定的数值就进行交换

    代码:

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. // 倒进数组里面
    15. void dfs(TreeNode* root, vector<int>& nums) {
    16. if (!root) {
    17. return;
    18. }
    19. if (root->left) {
    20. dfs(root->left, nums);
    21. }
    22. nums.push_back(root->val);
    23. if (root->right) {
    24. dfs(root->right, nums);
    25. }
    26. }
    27. // 查找对应位置
    28. pair<int, int> findPos(vector<int>& nums) {
    29. int lp = 0, rp = 0;
    30. int n = nums.size();
    31. pair<int, int> pos;
    32. int cnt = 0;
    33. for (int i = 0; i < n - 1; ++i) {
    34. if (nums[i] > nums[i + 1]) {
    35. pos.first = nums[i];
    36. break;
    37. }
    38. }
    39. for (int i = n - 1; i > 0; --i) {
    40. if (nums[i] < nums[i - 1]) {
    41. pos.second = nums[i];
    42. break;
    43. }
    44. }
    45. return pos;
    46. }
    47. // 交换位置
    48. void exchange(TreeNode* root, int x, int y, int cnt) {
    49. if (!root) {
    50. return;
    51. }
    52. if (root->val == x && cnt <= 1) {
    53. root->val = y;
    54. cnt += 1;
    55. } else if (root->val == y && cnt <= 1) {
    56. root->val = x;
    57. cnt += 1;
    58. }
    59. if (root->left) exchange(root->left, x, y, cnt);
    60. if (root->right) exchange(root->right, x, y, cnt);
    61. }
    62. void recoverTree(TreeNode* root) {
    63. // 三步走:1.倒进一个数组当中 2.找到节点对应数值 3,进行交换
    64. vector<int> nums;
    65. dfs(root, nums);
    66. // for (int i = 0, n = nums.size(); i < n; ++i) {
    67. // cout << nums[i] << " ";
    68. // }
    69. // cout << endl;
    70. pair<int, int> pos = findPos(nums);
    71. // cout << pos.first << " " << pos.second << endl;
    72. exchange(root, pos.first, pos.second, 0);
    73. }
    74. };