Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ef1bfe7

Browse files
committedFeb 2, 2023
Add solution #99
1 parent c81c499 commit ef1bfe7

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,7 @@
8585
95|[Unique Binary Search Trees II](./0095-unique-binary-search-trees-ii.js)|Medium|
8686
96|[Unique Binary Search Trees](./0096-unique-binary-search-trees.js)|Medium|
8787
98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium|
88+
99|[Recover Binary Search Tree](./0099-recover-binary-search-tree.js)|Medium|
8889
100|[Same Tree](./0100-same-tree.js)|Easy|
8990
101|[Symmetric Tree](./0101-symmetric-tree.js)|Easy|
9091
102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium|
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 99. Recover Binary Search Tree
3+
* https://leetcode.com/problems/recover-binary-search-tree/
4+
* Difficulty: Medium
5+
*
6+
* You are given the root of a binary search tree (BST), where the values
7+
* of exactly two nodes of the tree were swapped by mistake. Recover the
8+
* tree without changing its structure.
9+
*/
10+
11+
/**
12+
* Definition for a binary tree node.
13+
* function TreeNode(val, left, right) {
14+
* this.val = (val===undefined ? 0 : val)
15+
* this.left = (left===undefined ? null : left)
16+
* this.right = (right===undefined ? null : right)
17+
* }
18+
*/
19+
/**
20+
* @param {TreeNode} root
21+
* @return {void} Do not return anything, modify root in-place instead.
22+
*/
23+
var recoverTree = function(root) {
24+
let [previous, small, large] = [null, null, null];
25+
26+
dfs(root);
27+
[large.val, small.val] = [small.val, large.val];
28+
29+
function dfs(root) {
30+
if (!root) return;
31+
dfs(root.left);
32+
if (previous != null && previous.val > root.val) {
33+
small = root;
34+
if (!large) {
35+
large = previous;
36+
} else {
37+
return false;
38+
}
39+
}
40+
previous = root;
41+
dfs(root.right);
42+
}
43+
};

0 commit comments

Comments
 (0)
Please sign in to comment.