Skip to content

Commit b0ad2bc

Browse files
committed
Java solution 98 && 99
1 parent 360bec9 commit b0ad2bc

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.Stack;
2+
3+
/**
4+
* Given a binary tree, determine if it is a valid binary search tree (BST).
5+
* <p>
6+
* Assume a BST is defined as follows:
7+
* The left subtree of a node contains only nodes with keys less than the node's key.
8+
* The right subtree of a node contains only nodes with keys greater than the node's key.
9+
* Both the left and right subtrees must also be binary search trees.
10+
* <p>
11+
* Example 1:
12+
* 2
13+
* / \
14+
* 1 3
15+
* Binary tree [2,1,3], return true.
16+
* Example 2:
17+
* 1
18+
* / \
19+
* 2 3
20+
* Binary tree [1,2,3], return false.
21+
* <p>
22+
* Created by drfish on 28/05/2017.
23+
*/
24+
public class _098ValidateBinarySearchTree {
25+
public boolean isValidBST(TreeNode root) {
26+
if (root == null) {
27+
return true;
28+
}
29+
Stack<TreeNode> stack = new Stack<>();
30+
TreeNode prev = null;
31+
while (root != null || !stack.isEmpty()) {
32+
while (root != null) {
33+
stack.push(root);
34+
root = root.left;
35+
}
36+
root = stack.pop();
37+
if (prev != null && prev.val >= root.val) {
38+
return false;
39+
}
40+
prev = root;
41+
root = root.right;
42+
}
43+
return true;
44+
}
45+
}

java/_099RecoverBinarySearchTree.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.Stack;
2+
3+
/**
4+
* Two elements of a binary search tree (BST) are swapped by mistake.
5+
* Recover the tree without changing its structure.
6+
* <p>
7+
* Note:
8+
* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
9+
* <p>
10+
* Created by drfish on 28/05/2017.
11+
*/
12+
public class _099RecoverBinarySearchTree {
13+
public void recoverTree(TreeNode root) {
14+
TreeNode first = null;
15+
TreeNode second = null;
16+
TreeNode prev = null;
17+
Stack<TreeNode> stack = new Stack<>();
18+
while (root != null || !stack.isEmpty()) {
19+
while (root != null) {
20+
stack.push(root);
21+
root = root.left;
22+
}
23+
root = stack.pop();
24+
if (prev != null && prev.val >= root.val) {
25+
if (first == null) {
26+
first = prev;
27+
}
28+
second = root;
29+
}
30+
prev = root;
31+
root = root.right;
32+
}
33+
swap(first, second);
34+
}
35+
36+
private void swap(TreeNode node1, TreeNode node2) {
37+
int temp = node1.val;
38+
node1.val = node2.val;
39+
node2.val = temp;
40+
}
41+
}

0 commit comments

Comments
 (0)