二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
    对于二叉搜索树,如果对其进行中序遍历,得到的值序列是递增有序的。
    leetcode-99:
    给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树

    1. const inorder = (root, nums) => {
    2. if (root === null) {
    3. return;
    4. }
    5. inorder(root.left, nums);
    6. nums.push(root.val);
    7. inorder(root.right, nums);
    8. }
    9. const findTwoSwapped = (nums) => {
    10. const n = nums.length;
    11. let index1 = -1, index2 = -1;
    12. for (let i = 0; i < n - 1; ++i) {
    13. if (nums[i + 1] < nums[i]) {
    14. index2 = i + 1;
    15. if (index1 === -1) {
    16. index1 = i;
    17. } else {
    18. break;
    19. }
    20. }
    21. }
    22. let x = nums[index1], y = nums[index2];
    23. return [x, y];
    24. }
    25. const recover = (r, count, x, y) => {
    26. if (r !== null) {
    27. if (r.val === x || r.val === y) {
    28. r.val = r.val === x ? y : x;
    29. if (--count === 0) {
    30. return;
    31. }
    32. }
    33. recover(r.left, count, x, y);
    34. recover(r.right, count, x, y);
    35. }
    36. }
    37. var recoverTree = function(root) {
    38. const nums = [];
    39. inorder(root, nums);
    40. const [first, second] = findTwoSwapped(nums);
    41. recover(root, 2, first, second);
    42. };