[英]One algorithm for binary tree search, traversal, insertion, and deletion
我看到二叉樹實現像這樣 :
var insert = function(value, root) {
if (!root) {
// Create a new root.
root = { val: value };
}
else {
var current = root;
while (current) {
if (value < current.val) {
if (!current.left) {
// Insert left child.
current.left = { val: value };
break;
}
else {
current = current.left;
}
}
else if (value > current.val) {
if (!current.right) {
// Insert right child.
current.right = { val: value };
break;
}
else {
current = current.right;
}
}
else {
// This value already exists. Ignore it.
break;
}
}
}
return root;
}
var exists = function(value, root) {
var result = false;
var current = root;
while (current) {
if (value < current.val) {
current = current.left;
}
else if (value > current.val) {
current = current.right;
}
else {
result = true;
break;
}
}
return result;
}
var traversePre = function(head, callback) {
// Preorder traversal.
if (head) {
if (callback) {
callback(head.val);
}
traversePre(head.left, callback);
traversePre(head.right, callback);
}
}
var traversePost = function(head, callback) {
// Postorder traversal.
if (head) {
traversePost(head.left, callback);
traversePost(head.right, callback);
if (callback) {
callback(head.val);
}
}
}
var traverseIn = function(head, callback) {
// Inorder traversal.
if (head) {
traverseIn(head.left, callback);
if (callback) {
callback(head.val);
}
traverseIn(head.right, callback);
}
}
var traverseInIterative = function(head, callback) {
// Inorder traversal (iterative style).
var current = head;
var history = [];
// Move down to the left-most smallest value, saving all nodes on the way.
while (current) {
history.push(current);
current = current.left;
}
current = history.pop();
while (current) {
if (callback) {
callback(current.val);
}
// Move to the right, and then go down to the left-most smallest value again.
current = current.right;
while (current) {
history.push(current);
current = current.left;
}
current = history.pop();
}
}
var root = insert(10);
insert(5, root);
insert(6, root);
insert(3, root);
insert(20, root);
特別是, traverseInIterative
對我來說看起來不錯。 但是我想知道是否真的需要insert
並exists
,以及是否同樣需要search
或delete
。 我發現(就像在這些實現中一樣)它們的實現方式有所不同,但是我想知道是否可以實現一個通用的匹配功能,一次解決所有性能,同時在性能方面達到理想。
設計執行所有操作的通用方法的一種方法是-
genericMethod(value, root, command)
在此, command
參數將接收一個指定insert
, delete
或search
的字符串。 基於命令參數,您可以調整內部實現以支持所有操作。
現在讓我們來談談性能和設計角度的問題。 我認為使用這種方法並不理想。 擁有這樣的通用方法會給您帶來比您想象的更多的問題。
現在,在檢查完您的代碼后-有很多可以改進的地方,根據我的看法,它們將為您帶來更好的體驗,例如-
exists()
方法,而不是在那些方法中編寫相同的代碼即可。 這種類型的通用行為確保您不會一次又一次地編寫相同的代碼,也不會重復編寫SRP(單一職責原理),因此您的代碼是完全分隔開的,並且更易於閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.