99. Recover Binary Search Tree
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. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {void} Do not return anything, modify root in-place instead. */ var recoverTree = function(root) { let list=[]; let vals=[]; inorder(root,vals,list); vals.sort((a,b)=>a-b); for(let i=0;i<list.length;i++){ list[i].val=vals[i]; } }; var inorder=function(root,vals,list){ if(!root) return ; inorder(root.left,vals,list); list.push(root); vals.push(root.val); inorder(root.right,vals,list); }