From b0ad2bc34d7ed85a76a9190d196e668dc8d9f779 Mon Sep 17 00:00:00 2001 From: Shen Jie Date: Sun, 28 May 2017 13:26:25 +0800 Subject: [PATCH] Java solution 98 && 99 --- java/_098ValidateBinarySearchTree.java | 45 ++++++++++++++++++++++++++ java/_099RecoverBinarySearchTree.java | 41 +++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 java/_098ValidateBinarySearchTree.java create mode 100644 java/_099RecoverBinarySearchTree.java diff --git a/java/_098ValidateBinarySearchTree.java b/java/_098ValidateBinarySearchTree.java new file mode 100644 index 0000000..2719148 --- /dev/null +++ b/java/_098ValidateBinarySearchTree.java @@ -0,0 +1,45 @@ +import java.util.Stack; + +/** + * Given a binary tree, determine if it is a valid binary search tree (BST). + *

+ * 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. + *

+ * Example 1: + * 2 + * / \ + * 1 3 + * Binary tree [2,1,3], return true. + * Example 2: + * 1 + * / \ + * 2 3 + * Binary tree [1,2,3], return false. + *

+ * Created by drfish on 28/05/2017. + */ +public class _098ValidateBinarySearchTree { + public boolean isValidBST(TreeNode root) { + if (root == null) { + return true; + } + Stack 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; + } +} diff --git a/java/_099RecoverBinarySearchTree.java b/java/_099RecoverBinarySearchTree.java new file mode 100644 index 0000000..afd6f7f --- /dev/null +++ b/java/_099RecoverBinarySearchTree.java @@ -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. + *

+ * Note: + * A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? + *

+ * 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 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; + } +}