iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
0
自我挑戰組

透過JavaScript學習演算法與資料結構系列 第 24

深度優先搜尋法(Depth Frist Search)

請看下圖的動態呈現。
img

簡而言之,深度優先搜尋法會先從root節點開始,先由左側的子節點往下找有無子節點,如果有就繼續往下找,如果沒有就回到上一層節點,找尋有無其他子節點,依此類推。

程式碼如下:

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) {
  (function recurse(currentNode) {
    callback(currentNode); 
    for (var i = 0, length = currentNode.children.length; i < length; i++) {
      recurse(currentNode.children[i]);
    }
  })(this._root);
};
const tree = new Tree('1');

tree._root.children.push(new Node('2'));
tree._root.children[0].parent = tree;

tree._root.children.push(new Node('5'));
tree._root.children[1].parent = tree;

tree._root.children[1].children.push(new Node('6'));
tree._root.children[1].children.push(new Node('8'));

tree._root.children[1].children[0].children.push(new Node('7'));

tree._root.children.push(new Node('9'));
tree._root.children[2].parent = tree;

tree._root.children[2].children.push(new Node('10'));

tree._root.children[0].children.push(new Node('3'));
tree._root.children[0].children[0].parent = tree._root.children[0];

tree._root.children[0].children[0].children.push(new Node('4'));
tree._root.children[0].children[0].children[0].parent = tree._root.children[0].children[0];

tree.traverseDF(function(node) {
  console.log(node.data)
});

程式碼


上一篇
雜湊表(Hash Table)
下一篇
廣度優先搜尋法(Breadth First Search)
系列文
透過JavaScript學習演算法與資料結構30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言