-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path099.js
More file actions
37 lines (35 loc) · 881 Bytes
/
099.js
File metadata and controls
37 lines (35 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 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) {
const inorderTraversal = root => {
if (root === null) return [];
return inorderTraversal(root.left).concat([root]).concat(inorderTraversal(root.right));
}
let error1 = null;
let error2 = null;
const list = inorderTraversal(root);
for (let i = 0; i < list.length - 1; ++i) {
const current = list[i];
const next = list[i + 1];
if (current.val > next.val) {
if (error1 === null) {
error1 = current;
error2 = next;
} else {
error2 = next;
}
}
}
const temp = error1.val;
error1.val = error2.val;
error2.val = temp;
};