【发布时间】:2010-10-04 17:46:22
【问题描述】:
我在这里读到了一个称为验证二叉搜索树的面试练习。
这究竟是如何工作的?在验证二叉搜索树时会寻找什么?我写了一个基本的搜索树,但从未听说过这个概念。
【问题讨论】:
-
使用中序遍历,检查每个元素是否大于前一个元素。
标签: algorithm data-structures binary-search-tree
我在这里读到了一个称为验证二叉搜索树的面试练习。
这究竟是如何工作的?在验证二叉搜索树时会寻找什么?我写了一个基本的搜索树,但从未听说过这个概念。
【问题讨论】:
标签: algorithm data-structures binary-search-tree
private void validateBinarySearchTree(Node node) {
if (node == null) return;
Node left = node.getLeft();
if (left != null) {
if (left.getData() < node.getData()) {
validateBinarySearchTree(left);
} else {
throw new IllegalStateException("Not a valid Binary Search tree");
}
}
Node right = node.getRight();
if (right != null) {
if (right.getData() > node.getData()) {
validateBinarySearchTree(right);
} else {
throw new IllegalStateException("Not a valid Binary Search tree");
}
}
}
【讨论】:
boolean isBST(Node root) {
if (root == null) { return true; }
return (isBST(root.left) && (isBST(root.right) && (root.left == null || root.left.data <= root.data) && (root.right == null || root.right.data > root.data));
}
【讨论】:
这是我用 JavaScript 编写的递归解决方案
function isBST(tree) {
if (tree === null) return true;
if (tree.left != undefined && tree.left.value > tree.value) {
return false;
}
if (tree.right != undefined && tree.right.value <= tree.value) {
return false;
}
return isBST(tree.left) && isBST(tree.right);
}
【讨论】: