【问题标题】:How do you validate a binary search tree?如何验证二叉搜索树?
【发布时间】:2010-10-04 17:46:22
【问题描述】:

我在这里读到了一个称为验证二叉搜索树的面试练习。

这究竟是如何工作的?在验证二叉搜索树时会寻找什么?我写了一个基本的搜索树,但从未听说过这个概念。

【问题讨论】:

  • 使用中序遍历,检查每个元素是否大于前一个元素。

标签: algorithm data-structures binary-search-tree


【解决方案1】:
 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");
        }
    }
}

【讨论】:

    【解决方案2】:
    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));
    }
    

    【讨论】:

      【解决方案3】:

      这是我用 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);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 2023-03-08
        • 2011-03-24
        相关资源
        最近更新 更多