Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hasBinarySearchProperty #16

Open
make-github-pseudonymous-again opened this issue Oct 27, 2020 · 0 comments
Open

hasBinarySearchProperty #16

make-github-pseudonymous-again opened this issue Oct 27, 2020 · 0 comments

Comments

@make-github-pseudonymous-again
Copy link
Owner

import {isSorted} from '@aureooms/js-sort';
const hasBinarySearchProperty = (compare, tree) => {
    const array = [...tree];
    return isSorted(compare, array, 0, array.length);
};
const hasBinarySearchPropertyAndDoesNotContainDuplicates = (compare, tree) => {
    const strictCompare = (a,b) => compare(a,b) <= 0 ? -1 : 1;
    // const strictCompare = (a,b) => compare(a,b) < 0 ? -1 : 1; // ugly because the choice of `<=` vs `<` depends on the implementation of `hasBinarySearchProperty` and actually does not work in the general case
    return hasBinarySearchProperty(strictCompare, tree);
const hasBinarySearchProperty = (compare, node, left = undefined, right = undefined) => {
    if (node === null) return true;
    if (left !== undefined && compare(node.key, left) < 0) return false;
    if (right !== undefined && compare(node.key, right) > 0) return false;
    //     if (right !== undefined && compare(right, node.key) < 0) return false; // if using the `strictCompare` trick
    return hasBinarySearchProperty(compare, node.left, left, node.key) && hasBinarySearchProperty(compare, node.right, node.key, right);
};

const hasBinarySearchPropertyAndDoesNotContainDuplicates = (compare, node, left = undefined, right = undefined) => {
    if (node === null) return true;
    if (left !== undefined && compare(node.key, left) <= 0) return false;
    if (right !== undefined && compare(node.key, right) >= 0) return false;
    return hasBinarySearchProperty(compare, node.left, left, node.key) && hasBinarySearchProperty(compare, node.right, node.key, right);
};

See https://en.wikipedia.org/wiki/Binary_search_tree#Verification

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant