請看下圖的動態呈現。
簡而言之,深度優先搜尋法會先從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)
});