class tree {
constructor (val) {
this.val = val
this.left = this.right = null
}
}
搜索二叉树:
class BST {
constructor (data) {
let len = data.length, i, root
for (i = 0; i < len; i++) {
let node = new tree(data[i])
if (!root) {
root = node
} else {
this.insertBST(root, node)
}
}
return root
}
insertBST(root, node) {
if (root.val > node.val) {
if (root.left === null) {
root.left = node
} else {
this.insertBST(root.left, node)
}
} else {
if (root.right === null) {
root.right = node
} else {
this.insertBST(root.right, node)