-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecover-binary-search-tree.js
More file actions
63 lines (47 loc) · 1.51 KB
/
recover-binary-search-tree.js
File metadata and controls
63 lines (47 loc) · 1.51 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Problem: Recover Binary Search Tree
* Link: https://leetcode.com/problems/recover-binary-search-tree/
* Difficulty: Medium
*
* Two nodes of a BST are swapped by mistake. Recover the tree without changing structure.
*
* Time Complexity: O(n)
* Space Complexity: O(h) for recursion, O(1) with Morris traversal
*/
// JavaScript Solution - Inorder traversal to find swapped nodes
function recoverTree(root) {
let first = null, second = null, prev = null;
function inorder(node) {
if (!node) return;
inorder(node.left);
// In correct BST, prev.val < node.val always
// If prev.val > node.val, we found a violation
if (prev && prev.val > node.val) {
if (!first) first = prev; // first violation: prev is the bad node
second = node; // second (or only) violation: node is the bad node
}
prev = node;
inorder(node.right);
}
inorder(root);
// Swap values of the two misplaced nodes
const temp = first.val;
first.val = second.val;
second.val = temp;
}
module.exports = recoverTree;
/* Python Solution:
def recoverTree(root):
first = second = prev = None
def inorder(node):
nonlocal first, second, prev
if not node: return
inorder(node.left)
if prev and prev.val > node.val:
if not first: first = prev
second = node
prev = node
inorder(node.right)
inorder(root)
first.val, second.val = second.val, first.val # swap
*/