二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
对于二叉搜索树,如果对其进行中序遍历,得到的值序列是递增有序的。
leetcode-99:
给你二叉搜索树的根节点 root ,该树中的 恰好 两个节点的值被错误地交换。请在不改变其结构的情况下,恢复这棵树 。
const inorder = (root, nums) => {if (root === null) {return;}inorder(root.left, nums);nums.push(root.val);inorder(root.right, nums);}const findTwoSwapped = (nums) => {const n = nums.length;let index1 = -1, index2 = -1;for (let i = 0; i < n - 1; ++i) {if (nums[i + 1] < nums[i]) {index2 = i + 1;if (index1 === -1) {index1 = i;} else {break;}}}let x = nums[index1], y = nums[index2];return [x, y];}const recover = (r, count, x, y) => {if (r !== null) {if (r.val === x || r.val === y) {r.val = r.val === x ? y : x;if (--count === 0) {return;}}recover(r.left, count, x, y);recover(r.right, count, x, y);}}var recoverTree = function(root) {const nums = [];inorder(root, nums);const [first, second] = findTwoSwapped(nums);recover(root, 2, first, second);};
