我们需要在BinarySearchTree数据类型的原型对象上编写一个JavaScript函数,该函数接受一个值并查找该值是否包含在BST中。
此代码将是-
// class for a single Node for BST class Node { constructor(value) { this.value = value; } } //BST的类 //包含插入节点并搜索现有节点的功能 class BinarySearchTree { constructor() { this._root = null; }; insert(value) { let node = this, side = '_root'; while (node[side]) { node = node[side]; if (value === node.value) { return; }; side = value < node.value ? 'left' : 'right'; }; node[side] = new Node(value); }; contains(value) { let current = this._root; while (current) { if (value === current.value) { return true; }; current = value < current.value ? current.left : current.right; } return false; }; } const tree = new BinarySearchTree(); for (let i = 0; i < 10; i++) { tree.insert(Math.floor(Math.random() * 1000)); }; tree.insert(34); console.log(tree.contains(34)); console.log(tree.contains(334));
输出结果
控制台中的输出将是-
true false