摘要:第二步自終止,第三步自調(diào)用,第四步回調(diào)函數(shù)會(huì)重復(fù)進(jìn)行,直到我們遍歷到樹的所有節(jié)點(diǎn)。執(zhí)行回調(diào)函數(shù),傳入賦值為第二層第二個(gè)子節(jié)點(diǎn)。
本文譯自Cho S. Kim的文章:Data Structures With JavaScript: Tree
“樹”,是web開發(fā)中最常用的數(shù)據(jù)結(jié)構(gòu)之一。這句話對(duì)開發(fā)者和用戶來(lái)講,都適用:開發(fā)人員通過(guò)HTML創(chuàng)造了一個(gè)DOM,用戶則通過(guò)DOM消費(fèi)網(wǎng)絡(luò)信息。
進(jìn)一步講,您正在閱讀的本文也是以樹的形式在瀏覽器中渲染的。文章中的段落由
標(biāo)簽中的文字所代表;
標(biāo)簽嵌套在元素中,而元素則是的子元素。
數(shù)據(jù)的嵌套類似一個(gè)家譜:元素是一個(gè)爹爹,元素是一個(gè)孩兒,
元素則是元素的孩兒。如果你感覺(jué)這種類比容易理解,那么在接下來(lái)實(shí)現(xiàn)一棵樹的過(guò)程中,更多的類比對(duì)你來(lái)說(shuō)應(yīng)該也不成問(wèn)題。
在本文中,我們將創(chuàng)建一顆有兩種遍歷方式的樹:Depth-First-Search(DFS)深度優(yōu)先搜索,和Breadth-First-Search(BFS)寬度優(yōu)先搜索(遍歷是指訪問(wèn)樹的每一個(gè)節(jié)點(diǎn))。這兩種遍歷方式各自強(qiáng)調(diào)了對(duì)一顆樹操作的不同姿勢(shì);而且他們用到了我們之前提過(guò)的( 沒(méi)翻,去找原文 )數(shù)據(jù)結(jié)構(gòu):DFS用到了棧,BFS用到了隊(duì)列。
樹(DFS 和 BFS)樹,是一種使用節(jié)點(diǎn)來(lái)模擬分等級(jí)(層次)數(shù)據(jù)的數(shù)據(jù)結(jié)構(gòu)。節(jié)點(diǎn)存儲(chǔ)數(shù)據(jù),并指向其他節(jié)點(diǎn)(每個(gè)節(jié)點(diǎn)都存儲(chǔ)有自身數(shù)據(jù),和指向其它節(jié)點(diǎn)的指針)。部分讀者可能對(duì)節(jié)點(diǎn)、指針等術(shù)語(yǔ)不太熟悉,所以我們這里做一個(gè)類比:把一棵樹比作一個(gè)組織結(jié)構(gòu)。這個(gè)組織結(jié)構(gòu)有一個(gè)最高負(fù)責(zé)人(根節(jié)點(diǎn)),比如說(shuō)總經(jīng)理。緊跟著就是在其之下的職位,比如說(shuō)一個(gè)副總。
我們用一個(gè)從老總指向副總的箭頭來(lái)表示這種關(guān)系。老總 → 副總。一個(gè)職位(老總),就是一個(gè)節(jié)點(diǎn);老總和副總之間的關(guān)系(箭頭),就是指針。在組織結(jié)構(gòu)圖中創(chuàng)建更多的類似關(guān)系,只需要重復(fù)上面的步驟,一個(gè)節(jié)點(diǎn)指向另外一個(gè)節(jié)點(diǎn)。
在概念上,我希望節(jié)點(diǎn)和指針能夠講得通。在實(shí)踐上,我們?cè)倏梢耘e一個(gè)DOM的栗子。一個(gè)DOM的根節(jié)點(diǎn)就是,它指向了和。然后重復(fù)下去生成一顆DOM樹。
這么搞最贊的一點(diǎn)就是它具有嵌套節(jié)點(diǎn)的能力:一個(gè),內(nèi)部可以有n個(gè)節(jié)點(diǎn),每個(gè)也可以有兄弟節(jié)點(diǎn)。(作者發(fā)出了奇怪的贊美)
樹跟節(jié)點(diǎn)可以用兩個(gè)多帶帶的構(gòu)造器來(lái)描述:Node和Tree。
data存儲(chǔ)一個(gè)值
parent指向這個(gè)節(jié)點(diǎn)的父節(jié)點(diǎn)
children指向表中的下一個(gè)節(jié)點(diǎn) (這個(gè)可能有一堆,那么可能是一個(gè)數(shù)組)
_root指向這個(gè)樹的根節(jié)點(diǎn)
traverseDF(callback)使用DFS遍歷樹的節(jié)點(diǎn)
traverseBF(callback)使用BFS遍歷樹的節(jié)點(diǎn)
contains(data,traversal)在樹里面搜索一個(gè)節(jié)點(diǎn)
add(data,toData,traverse)向樹添加一個(gè)節(jié)點(diǎn)
remove(child,parent)刪除樹的一個(gè)節(jié)點(diǎn)
實(shí)現(xiàn)一棵樹下面開始寫代碼!
function Node(data) { this.data = data; this.parent = null; this.children = []; }
每個(gè)Node的實(shí)例都包含三個(gè)屬性,data,parent和children。第一個(gè)屬性保存跟這個(gè)節(jié)點(diǎn)有關(guān)的數(shù)據(jù),比如“村長(zhǎng)”。第二個(gè)屬性指向一個(gè)節(jié)點(diǎn)(在js中,就是等于號(hào),比如this.parent = someOtherNode 這個(gè)就實(shí)現(xiàn)指針了好吧。什么值傳遞就不細(xì)展開了。其他算法中的指針實(shí)現(xiàn)也類似。)。
function Tree(data) { var node = new Node(data); this._root = node; }
Tree包含兩行代碼,第一行創(chuàng)建了一個(gè)Node的實(shí)例node,第二行把這個(gè)node賦值給了this._root。就是對(duì)一個(gè)樹進(jìn)行了初始化,給了它一個(gè)根節(jié)點(diǎn)。
Tree和Node的定義只需要很少的代碼,但是這些代碼已經(jīng)足夠我們模擬一個(gè)有層次的數(shù)據(jù)結(jié)構(gòu)。為了說(shuō)明這一點(diǎn),我們可以通過(guò)用一點(diǎn)測(cè)試數(shù)據(jù)來(lái)創(chuàng)建Tree的實(shí)例(間接也創(chuàng)建了Node的實(shí)例):
var tree = new Tree("CEO"); tree._root; // 返回{data: "CEO", parent: null, children: []}
有parent和children的存在,我們可以把節(jié)點(diǎn)添加為_root的子節(jié)點(diǎn),同時(shí)把這些子節(jié)點(diǎn)的父節(jié)點(diǎn)賦值為_root。
接下來(lái),我們給樹添加下面這5個(gè)方法:
traverseDF(callback)
traverseBF(callback)
contains(data,traversal)
add(child,parent)
remove(node,parent)
這些方法都需要對(duì)樹進(jìn)行遍歷,我們首先來(lái)實(shí)現(xiàn)遍歷方法(們)。
對(duì)樹進(jìn)行深度優(yōu)先遍歷:
Tree.prototype.traverseDF = function(callback) { // 一個(gè)遞歸,立即執(zhí)行函數(shù) (function recurse(currentNode) { // 第二步 for (var i = 0, length = currentNode.children.length; i < length; i++) { // 第三步 recurse(currentNode.children[i]); } // 第四步 callback(currentNode); // 首先執(zhí)行 })(this._root); };
traverseDF(callback)有一個(gè)callback參數(shù),顧名思義,callback是一個(gè)稍后會(huì)在traverseDF(callback)內(nèi)調(diào)用的函數(shù)。
traverseDF(callback)內(nèi)包含了一個(gè)叫做recurse的函數(shù)。recurse的意思是遞歸,這是一個(gè)遞歸函數(shù),用人話說(shuō)就是這個(gè)函數(shù)會(huì)調(diào)用自己,然后(特定條件下)自動(dòng)結(jié)束。注意上面代碼注釋中的第*步,我會(huì)用他們來(lái)描述一下recurse函數(shù)是怎么遍歷到整棵樹的:
首先執(zhí)行: recurse,以樹的根節(jié)點(diǎn)作為參數(shù)。此時(shí),currentNode指向這個(gè)根節(jié)點(diǎn)。
第二步: 進(jìn)入到一個(gè)for循環(huán),對(duì)currentNode(比如說(shuō)根節(jié)點(diǎn))的每一個(gè)子節(jié)點(diǎn)進(jìn)行迭代,從第一個(gè)開始。
第三步: 在for循環(huán)體內(nèi),調(diào)用recurse,傳參currentNode的某一個(gè)子節(jié)點(diǎn)。具體哪一個(gè)子節(jié)點(diǎn)取決于for循環(huán)的迭代情況。
第四步: 當(dāng)currentNode沒(méi)有更多的子節(jié)點(diǎn),退出for循環(huán),并調(diào)用在調(diào)用traverseDf(callback)時(shí)傳遞進(jìn)來(lái)的callback函數(shù)。
第二步(自終止),第三步(自調(diào)用),第四步(回調(diào)函數(shù)) 會(huì)重復(fù)進(jìn)行,直到我們遍歷到樹的所有節(jié)點(diǎn)。
完整的講述遞歸需要一整面文章,這超出了本文的范圍。讀者可以用上面的traverseDF(callback)來(lái)實(shí)驗(yàn)(在瀏覽器里面打個(gè)斷點(diǎn)看看是怎么執(zhí)行的),來(lái)嘗試?yán)斫馑窃趺垂ぷ鞯摹?/p>
下面這段例子用來(lái)說(shuō)明一個(gè)樹是如何被traverseDF(callback)遍歷的。
首先我們創(chuàng)建一顆樹用來(lái)遍歷,下面這種方法并不好,但是可以起到說(shuō)明的效果。理想的方式是使用后面在第四部分要實(shí)現(xiàn)的add(value)。
/* 建立一顆結(jié)構(gòu)如下的樹 one ├── two │ ├── five │ └── six ├── three └── four └── seven */ var tree = new Tree("one"); tree._root.children.push(new Node("two")); tree._root.children[0].parent = tree; tree._root.children.push(new Node("three")); tree._root.children[1].parent = tree; tree._root.children.push(new Node("four")); tree._root.children[2].parent = tree; tree._root.children[0].children.push(new Node("five")); tree._root.children[0].children[0].parent = tree._root.children[0]; tree._root.children[0].children.push(new Node("six")); tree._root.children[0].children[1].parent = tree._root.children[0]; tree._root.children[2].children.push(new Node("seven")); tree._root.children[2].children[0].parent = tree._root.children[2];
然后我們調(diào)用traverseDF(callback):
tree.traverseDF(function(node) { console.log(node.data) }); /* logs the following strings to the console(這個(gè)就不翻了) "five" "six" "two" "three" "seven" "four" "one" */
這個(gè)方法用來(lái)進(jìn)行寬度優(yōu)先遍歷。
深度優(yōu)先和寬度優(yōu)先的遍歷順序是不一樣的,我們使用在traverseBF(callback)中用過(guò)的樹來(lái)證明這一點(diǎn):
/* tree one (depth: 0) ├── two (depth: 1) │ ├── five (depth: 2) │ └── six (depth: 2) ├── three (depth: 1) └── four (depth: 1) └── seven (depth: 2) */
然后傳入相同的回調(diào)函數(shù):
tree.traverseBF(function(node) { console.log(node.data) }); /* logs the following strings to the console "one" "two" "three" "four" "five" "six" "seven" */
上面的log和樹的結(jié)構(gòu)已經(jīng)說(shuō)明了寬度優(yōu)先遍歷的模式。從根節(jié)點(diǎn)開始,然后向下一層,從左向右遍歷所有這一層的節(jié)點(diǎn)。重復(fù)進(jìn)行知道到達(dá)最底層。
現(xiàn)在我們有了概念,那么來(lái)實(shí)現(xiàn)代碼:
Tree.prototype.traverseBF = function(callback) { var queue = new Queue(); queue.enqueue(this._root); currentNode = queue.dequeue(); while(currentNode){ for (var i = 0, length = currentNode.children.length; i < length; i++) { queue.enqueue(currentNode.children[i]); } callback(currentNode); currentNode = queue.dequeue(); } };
traverseBF(callback)的定義包含了很多邏輯,作者在這里解釋了一堆。我感覺(jué)對(duì)理解代碼并沒(méi)有幫助。
嘗試解釋一下,根節(jié)點(diǎn)算第一層:
從根節(jié)點(diǎn)開始,這個(gè)時(shí)候currentNode是根節(jié)點(diǎn);
第一次while遍歷currentNode的所有子節(jié)點(diǎn),推進(jìn)隊(duì)列。(這個(gè)時(shí)候第二層已經(jīng)遍歷到了,并且會(huì)在while循環(huán)中依次執(zhí)行,先進(jìn)先出)
執(zhí)行回調(diào)函數(shù),傳入currentNode;
currentNode賦值為第二層第一個(gè)子節(jié)點(diǎn)。
第二次while:對(duì)currentNode,第二層第一個(gè)子節(jié)點(diǎn)的所有子節(jié)點(diǎn)遍歷,推入隊(duì)列。注意這里是第三層的第一部分。
執(zhí)行回調(diào)函數(shù),傳入currentNode;
currentNode賦值為第二層第二個(gè)子節(jié)點(diǎn)。
第三次while:對(duì)currentNode,第二層第二個(gè)子節(jié)點(diǎn)的所有子節(jié)點(diǎn)遍歷,推入隊(duì)列。注意這里是第三層的第二部分。
執(zhí)行回調(diào)函數(shù),傳入currentNode;
currentNode賦值為第二層第三個(gè)子節(jié)點(diǎn)。
最后幾次while
:這個(gè)時(shí)候已經(jīng)沒(méi)有下一層了,不會(huì)進(jìn)入for循環(huán),就是依次把隊(duì)列里剩的節(jié)點(diǎn)傳到回調(diào)函數(shù)里面執(zhí)行就對(duì)了。
這樣就很清楚了。
這個(gè)方法用來(lái)在樹里搜索一個(gè)特定的值。為了使用我們之前定義的兩種遍歷方式,contains(callback,traversal)可以接受兩個(gè)參數(shù),要找的值,和要進(jìn)行的遍歷方式。
Tree.prototype.contains = function(callback, traversal) { traversal.call(this, callback); };
call方法的第一個(gè)參數(shù)把traversal綁定在調(diào)用contains(callback,traversal)的那棵樹上面,第二個(gè)參數(shù)是一個(gè)在每個(gè)節(jié)點(diǎn)上面調(diào)用的函數(shù)。
下面這個(gè)函數(shù)大家自己理解,我感覺(jué)原作者解釋反了。
// tree is an example of a root node tree.contains(function(node){ if (node.data === "two") { console.log(node); } }, tree.traverseBF);
現(xiàn)在我們會(huì)找了,再來(lái)個(gè)添加的方法吧。
Tree.prototype.add = function(data, toData, traversal) { //實(shí)例一個(gè)node var child = new Node(data), parent = null, //找爹函數(shù) callback = function(node) { if (node.data === toData) { parent = node; } }; //按某種方式執(zhí)行找爹函數(shù) this.contains(callback, traversal); //找到了嗎 if (parent) { //找到了,領(lǐng)走,認(rèn)爹 parent.children.push(child); child.parent = parent; } else { //沒(méi)找到,報(bào)錯(cuò):沒(méi)這個(gè)爹 throw new Error("Cannot add node to a non-existent parent."); } };
注釋就很清楚了。
var tree = new Tree("CEO"); tree.add("VP of Happiness", "CEO", tree.traverseBF); /* our tree "CEO" └── "VP of Happiness" */
var tree = new Tree("CEO"); tree.add("VP of Happiness", "CEO", tree.traverseBF); tree.add("VP of Finance", "CEO", tree.traverseBF); tree.add("VP of Sadness", "CEO", tree.traverseBF); tree.add("Director of Puppies", "VP of Finance", tree.traverseBF); tree.add("Manager of Puppies", "Director of Puppies", tree.traverseBF); /* tree "CEO" ├── "VP of Happiness" ├── "VP of Finance" │ ├── "Director of Puppies" │ └── "Manager of Puppies" └── "VP of Sadness" */
類似的,刪除方法:
Tree.prototype.remove = function(data, fromData, traversal) { var tree = this, parent = null, childToRemove = null, index; //因?yàn)槭莿h除某個(gè)數(shù)據(jù)下的某個(gè)值,所以先定義找爹 var callback = function(node) { if (node.data === fromData) { parent = node; } }; //按某種方式找爹 this.contains(callback, traversal); //爹存在嗎 if (parent) { //存在,找娃的排行 index = findIndex(parent.children, data); //找著了嗎 if (index === undefined) { //妹找著 throw new Error("Node to remove does not exist."); } else { //找著了,干掉,提頭 childToRemove = parent.children.splice(index, 1); } } else { //爹不存在,報(bào)錯(cuò) throw new Error("Parent does not exist."); } //拿頭交差 return childToRemove; };
function findIndex(arr, data) { var index; //遍歷某個(gè)data爹的娃,如果全等,那么返回這個(gè)娃的排行,否則返回的index等于undefined for (var i = 0; i < arr.length; i++) { if (arr[i].data === data) { index = i; } } return index; }在全文的最后,作者放出了全家福:
function Node(data) { this.data = data; this.parent = null; this.children = []; } function Tree(data) { var node = new Node(data); this._root = node; } Tree.prototype.traverseDF = function(callback) { // this is a recurse and immediately-invoking function (function recurse(currentNode) { // step 2 for (var i = 0, length = currentNode.children.length; i < length; i++) { // step 3 recurse(currentNode.children[i]); } // step 4 callback(currentNode); // step 1 })(this._root); }; Tree.prototype.traverseBF = function(callback) { var queue = new Queue(); queue.enqueue(this._root); currentTree = queue.dequeue(); while(currentTree){ for (var i = 0, length = currentTree.children.length; i < length; i++) { queue.enqueue(currentTree.children[i]); } callback(currentTree); currentTree = queue.dequeue(); } }; Tree.prototype.contains = function(callback, traversal) { traversal.call(this, callback); }; Tree.prototype.add = function(data, toData, traversal) { var child = new Node(data), parent = null, callback = function(node) { if (node.data === toData) { parent = node; } }; this.contains(callback, traversal); if (parent) { parent.children.push(child); child.parent = parent; } else { throw new Error("Cannot add node to a non-existent parent."); } }; Tree.prototype.remove = function(data, fromData, traversal) { var tree = this, parent = null, childToRemove = null, index; var callback = function(node) { if (node.data === fromData) { parent = node; } }; this.contains(callback, traversal); if (parent) { index = findIndex(parent.children, data); if (index === undefined) { throw new Error("Node to remove does not exist."); } else { childToRemove = parent.children.splice(index, 1); } } else { throw new Error("Parent does not exist."); } return childToRemove; }; function findIndex(arr, data) { var index; for (var i = 0; i < arr.length; i++) { if (arr[i].data === data) { index = i; } } return index; }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/83910.html
摘要:前沿前端中設(shè)計(jì)數(shù)據(jù)結(jié)構(gòu)的方面不多,最常用的就是對(duì)樹結(jié)構(gòu)的一些操作。畢竟,就是天然的樹結(jié)構(gòu)。遞歸輸出非遞歸輸出業(yè)務(wù)場(chǎng)景前端中的樹操作,經(jīng)常是生成特定的樹結(jié)構(gòu)。 前沿 ????前端中設(shè)計(jì)數(shù)據(jù)結(jié)構(gòu)的方面不多,最常用的就是對(duì)樹結(jié)構(gòu)的一些操作。從某種意義上來(lái)說(shuō),前端工作本身就是和樹結(jié)構(gòu)打交道的一個(gè)工作方向。畢竟,DOM就是天然的樹結(jié)構(gòu)。所以如何能夠良好地對(duì)樹結(jié)構(gòu)進(jìn)行操作,是前端工程師不可或缺的一...
摘要:原文博客地址學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)四樹知乎專欄簡(jiǎn)書專題前端進(jìn)擊者知乎前端進(jìn)擊者簡(jiǎn)書博主博客地址的個(gè)人博客人之所能,不能兼?zhèn)?,棄其所短,取其所長(zhǎng)。通常子樹被稱作左子樹和右子樹。敬請(qǐng)期待數(shù)據(jù)結(jié)構(gòu)篇最后一篇文章學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)五圖參考文章樹數(shù)據(jù)結(jié)構(gòu)二叉樹 前言 總括: 本文講解了數(shù)據(jù)結(jié)構(gòu)中的[樹]的概念,盡可能通俗易懂的解釋樹這種數(shù)據(jù)結(jié)構(gòu)的概念,使用javascript實(shí)現(xiàn)了樹,如有紕漏,歡迎批評(píng)指正。 ...
摘要:像剛才的這幅圖,就是二叉搜索樹。而我們本文要學(xué)習(xí)的內(nèi)容,就是如何寫一個(gè)二叉搜索樹。但在二叉搜索樹中,我們把節(jié)點(diǎn)成為鍵,這是術(shù)語(yǔ)。前端路漫漫,且行且歌的前端樂(lè)園原文鏈接寒假前端學(xué)習(xí)學(xué)習(xí)數(shù)據(jù)結(jié)構(gòu)與算法四二叉搜索樹 本系列的第一篇文章: 學(xué)習(xí)JavaScript數(shù)據(jù)結(jié)構(gòu)與算法(一),棧與隊(duì)列第二篇文章:學(xué)習(xí)JavaScript數(shù)據(jù)結(jié)構(gòu)與算法(二):鏈表第三篇文章:學(xué)習(xí)JavaScript數(shù)據(jù)...
摘要:渲染樹的布局創(chuàng)建渲染器并將其添加到樹中時(shí),它沒(méi)有位置和大小,計(jì)算這些值稱為布局。根渲染器的位置為,其尺寸與瀏覽器窗口的可見部分即的大小相同。渲染器使其在屏幕上的矩形無(wú)效,這會(huì)導(dǎo)致操作系統(tǒng)將其視為需要重新繪制并生成繪事件的區(qū)域。 這是專門探索 JavaScript 及其所構(gòu)建的組件的系列文章的第11篇。 想閱讀更多優(yōu)質(zhì)文章請(qǐng)猛戳GitHub博客,一年百來(lái)篇優(yōu)質(zhì)文章等著你! 如果你錯(cuò)過(guò)了前...
摘要:每個(gè)列表中的數(shù)據(jù)項(xiàng)稱為元素。棧被稱為一種后入先出,的數(shù)據(jù)結(jié)構(gòu)。散列使用的數(shù)據(jù)結(jié)構(gòu)叫做散列表。不包含任何成員的集合稱為空集,全集則是包含一切可能成員的集合。因此二叉搜索樹需要平衡,即左右子樹高度要相近。 樓樓非計(jì)算機(jī)專業(yè),但是對(duì)計(jì)算機(jī)也還算喜歡。個(gè)人理解若有偏差,歡迎各位批評(píng)指正! 對(duì)于數(shù)據(jù)結(jié)構(gòu)和算法一直是我的薄弱環(huán)節(jié),相信大多數(shù)前端工程師可能多少會(huì)有些這方面的弱點(diǎn),加上數(shù)據(jù)結(jié)構(gòu)和算法本...
閱讀 1287·2021-11-24 09:39
閱讀 2211·2021-11-22 13:54
閱讀 2256·2021-09-08 10:45
閱讀 1525·2021-08-09 13:43
閱讀 3042·2019-08-30 15:52
閱讀 3167·2019-08-29 15:38
閱讀 2903·2019-08-26 13:44
閱讀 3114·2019-08-26 13:30