Skip to content

Commit 1b2d649

Browse files
solves leetcode #99 recover bst in java
1 parent 3d90a93 commit 1b2d649

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@
9191
| 96 | [Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees) | [![Java](assets/java.png)](src/UniqueBinarySearchTrees.java) | |
9292
| 97 | [Interleaving String](https://leetcode.com/problems/interleaving-string) | [![Java](assets/java.png)](src/InterleavingString.java) | |
9393
| 98 | [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree) | [![Java](assets/java.png)](src/ValidateBinarySearchTree.java) | |
94-
| 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree) | | |
94+
| 99 | [Recover Binary Search Tree](https://leetcode.com/problems/recover-binary-search-tree) | [![Java](assets/java.png)](src/RecoverBinarySearchTree.java) | |
9595
| 100 | [Same Tree](https://leetcode.com/problems/same-tree) | [![Java](assets/java.png)](src/SameTree.java) [![Python](assets/python.png)](python/same_tree.py) | |
9696
| 101 | [Symmetric Tree](https://leetcode.com/problems/symmetric-tree) | [![Java](assets/java.png)](src/SymmetricTree.java) [![Python](assets/python.png)](python/symmetric_tree.py) | |
9797
| 102 | [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal) | [![Java](assets/java.png)](src/BinaryTreeLevelOrderTraversal.java) | |

Diff for: src/RecoverBinarySearchTree.java

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// https://leetcode.com/problems/recover-binary-search-tree
2+
// T: O(n)
3+
// S: O(log(n))
4+
5+
public class RecoverBinarySearchTree {
6+
TreeNode first, second, previous = new TreeNode(Integer.MIN_VALUE);
7+
8+
public void recoverTree(TreeNode root) {
9+
inorder(root);
10+
swapValues(first, second);
11+
}
12+
13+
private void inorder(TreeNode root) {
14+
if (root == null) return;
15+
inorder(root.left);
16+
17+
if (first == null && root.val < previous.val) {
18+
first = previous;
19+
}
20+
if (first != null && root.val < previous.val) {
21+
second = root;
22+
}
23+
previous = root;
24+
25+
inorder(root.right);
26+
}
27+
28+
private void swapValues(TreeNode a, TreeNode b) {
29+
int temp = a.val;
30+
a.val = b.val;
31+
b.val = temp;
32+
}
33+
}

0 commit comments

Comments
 (0)