Question
package net.mooctest;
import java.util.LinkedList;
/**
* 验证二叉搜索树
*
* @author LeetCode
*
*/
public class ValidateBinarySearchTree {
LinkedList<TreeNode> stack = new LinkedList();
LinkedList<Integer> uppers = new LinkedList(),
lowers = new LinkedList();
public void update(TreeNode root, Integer lower, Integer upper) {
stack.add(root);
lowers.add(lower);
uppers.add(upper);
}
public boolean isValidBST(TreeNode root) {
Integer lower = null, upper = null, val;
update(root, lower, upper);
while (!stack.isEmpty()) {
root = stack.poll();
lower = lowers.poll();
upper = uppers.poll();
if (root == null) continue;
val = root.val;
if (lower != null && val <= lower) return false;
if (upper != null && val >= upper) return false;
update(root.right, val, upper);
update(root.left, lower, val);
}
return true;
}
}
package net.mooctest;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
ANSWER
package net.mooctest;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
public class TreeNodeTest {
@Test(timeout = 4000)
public void test() throws Throwable {
// Empty tree is a valid BST
assertEquals(true,new ValidateBinarySearchTree().isValidBST(null));
// Single node is a valid BST
assertEquals(true,new ValidateBinarySearchTree().isValidBST(new TreeNode(0)));
// Not a valid BST (violates the requirement of bigger than the left node)
TreeNode t0= new TreeNode(0);
t0.left = new TreeNode(1);
assertEquals(false,new ValidateBinarySearchTree().isValidBST(t0));
// Not a valid BST (violates the requirement of smaller than the right node)
TreeNode t1= new TreeNode(10);
t1.right = new TreeNode(9);
assertEquals(false,new ValidateBinarySearchTree().isValidBST(t1));
// Valid BST (with multiple levels)
TreeNode t2 = new TreeNode(5);
t2.left = new TreeNode(1);
t2.right = new TreeNode(7);
t2.right.left = new TreeNode(6);
t2.right.right = new TreeNode(8);
assertEquals(true,new ValidateBinarySearchTree().isValidBST(t2));
// Not a valid BST (with multiple levels)
TreeNode t3 = new TreeNode(5);
t3.left = new TreeNode(1);
t3.right = new TreeNode(4);
t3.right.left = new TreeNode(3);
t3.right.right = new TreeNode(6);
assertEquals(false,new ValidateBinarySearchTree().isValidBST(t3));
// Not a valid BST (with multiple levels)
TreeNode t4 = new TreeNode(5);
t4.left = new TreeNode(4);
t4.left.left = new TreeNode(1);
t4.left.right = new TreeNode(7);
t4.left.right.left = new TreeNode(6);
t4.left.right.right = new TreeNode(8);
assertEquals(false,new ValidateBinarySearchTree().isValidBST(t4));
}
}