Skip to content

Commit

Permalink
Java solution 98 && 99
Browse files Browse the repository at this point in the history
  • Loading branch information
gavinfish committed May 28, 2017
1 parent 360bec9 commit b0ad2bc
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 0 deletions.
45 changes: 45 additions & 0 deletions java/_098ValidateBinarySearchTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import java.util.Stack;

/**
* Given a binary tree, determine if it is a valid binary search tree (BST).
* <p>
* Assume a BST is defined as follows:
* The left subtree of a node contains only nodes with keys less than the node's key.
* The right subtree of a node contains only nodes with keys greater than the node's key.
* Both the left and right subtrees must also be binary search trees.
* <p>
* Example 1:
* 2
* / \
* 1 3
* Binary tree [2,1,3], return true.
* Example 2:
* 1
* / \
* 2 3
* Binary tree [1,2,3], return false.
* <p>
* Created by drfish on 28/05/2017.
*/
public class _098ValidateBinarySearchTree {
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode prev = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (prev != null && prev.val >= root.val) {
return false;
}
prev = root;
root = root.right;
}
return true;
}
}
41 changes: 41 additions & 0 deletions java/_099RecoverBinarySearchTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import java.util.Stack;

/**
* Two elements of a binary search tree (BST) are swapped by mistake.
* Recover the tree without changing its structure.
* <p>
* Note:
* A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
* <p>
* Created by drfish on 28/05/2017.
*/
public class _099RecoverBinarySearchTree {
public void recoverTree(TreeNode root) {
TreeNode first = null;
TreeNode second = null;
TreeNode prev = null;
Stack<TreeNode> stack = new Stack<>();
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if (prev != null && prev.val >= root.val) {
if (first == null) {
first = prev;
}
second = root;
}
prev = root;
root = root.right;
}
swap(first, second);
}

private void swap(TreeNode node1, TreeNode node2) {
int temp = node1.val;
node1.val = node2.val;
node2.val = temp;
}
}

0 comments on commit b0ad2bc

Please sign in to comment.