我的问题是如何将insert
的递归版本简化为二进制搜索树。假设我想从值数组中创建BST。
这是我在JavaScript中的方式(这些是BST类的方法)。
_insert(target, key) {
if (target.key > key) {
if (!target.left) {
target.left = new Node(key);
} else {
this._insert(target.left, key);
}
} else {
if (!target.right) {
target.right = new Node(key);
} else {
this._insert(target.right, key);
}
}
}
insert(key) {
if (!this.root) {
this.root = new Node(key);
} else {
this._insert(this.root, key);
}
}
fill(keys) { keys.forEach(k => this.insert(k)); }
另一方面,在Haskell中我会做这样的事情:
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
insert :: (Ord a) => a -> Tree a -> Tree a
insert x EmptyTree = singleton x
insert x t@(Node a left right)
| x == a = t
| x < a = Node a (insert x left) right
| x > a = Node a left (insert x right)
fill :: (Ord a) => [a] -> Tree a
fill [] = EmptyTree
fill xs = foldr insert EmptyTree $ reverse xs
Haskell版本显然比JavaScript版本更简洁,更易于阅读。
我的问题是,我可以以某种方式简化JavaScript版本,使其更像“Haskell”(我知道我可以将这些方法重写为函数,而不需要BST类,但代码将非常类似于这个)? JavaScript代码是我想出的最佳代码。