leetCode-Record icon indicating copy to clipboard operation
leetCode-Record copied to clipboard

99. 恢复二叉搜索树

Open fireairforce opened this issue 5 years ago • 0 comments

这题来个中序遍历比较一波,然后换值就可以了:

/**
 * 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) {
   if(!root) {
       return;
   }
   let t1,t2,pre;
    const inorder = (root) => {
        if(!root) {
            return;
        }
        inorder(root.left);
        if(pre && pre.val > root.val) {
            if(!t1) {
                t1 = pre;
            }
            t2 = root;
        }
        pre = root;
        inorder(root.right);
    }
    inorder(root);
    let temp = t1.val;
    t1.val = t2.val;
    t2.val = temp;
};

fireairforce avatar Mar 03 '20 08:03 fireairforce