多叉树可以实现复杂的数据结构的存储,通过遍历方法可以方便高效的查找数据,提高查找的效率,同时方便管理节点数据。javascript的DOM其实就是以多叉树的形式存储的。下面用javascript来实现多叉树的数据结构
1、创造一个节点
数据是以节点的形式存储的:
class Node {
constructor(data) {
this.data = data;
this.parent = null;
this.children = [];
}
}
2、创造树
树用来连接节点,就像真实世界树的主干一样,延伸着很多分支
class MultiwayTree {
constructor() {
this._root = null;
}
}
3、添加一个节点
function add(data, toData, traversal) {
let node = new Node(data)
// 第一次添加到根节点
// 返回值为this,便于链式添加节点
if (this._root === null) {
this._root = node;
return this;
}
let parent = null,
callback = function(node) {
if (node.data === toData) {
parent = node;
return true;
}
};
// 根据遍历方法查找父节点(遍历方法后面会讲到),然后把节点添加到父节点
// 的children数组里
// 查找方法contains后面会讲到
this.contains(callback, traversal);
if (parent) {
parent.children.push(node);
node.parent = parent;
return this;
} else {
throw new Error('Cannot add node to a non-existent parent.');
}
}
4、深度优先遍历
深度优先会尽量先从子节点查找,子节点查找完再从兄弟节点查找,适合数据深度比较大的情况,如文件目录
function traverseDF(callback) {
let stack = [], found = false;
stack.unshift(this._root);
le