/*
树的操作:添加、删除、查找、修改
树节点数据 - 父子
*/
class Tree{
constructor(value) {
this.root = new TreeNode(value);
}
getRoot() {
return this.root;
}
getById(id) {
function find(node) {
if(node.id === id) {
return node;
} else {
for(let i = 0; i < node.childNode.length; i++) {
let res = find(node.childNode[i]);
if(res) return res;
}
}
}
return find(this.root)
}
}
class TreeNode{
constructor(value) {
this.value = value;
this.parentNode = null;
this.childNode = [];
this.id = undefined;
}
// 添加子节点
appendChild(node) {
this.childNode.push(node);
node.parentNode = this;
}
// 删掉某个子节点
removeChild(node) {
// 先按照最底层的写法实现
for(let i = 0; i < this.childNode.length; i++){
if(this.childNode[i] === node) {
this.childNode.splice(i, 1);
node.parentNode = undefined;
return ;
}
}
}
// 查找节点
}
const tree = new Tree('html');
const root = tree.getRoot();
const header = new TreeNode('header');
const body = new TreeNode('body');
const p = new TreeNode('p');
p.id = 'p1'
root.appendChild(header);
root.appendChild(body);
body.appendChild(p);
console.log(tree.getById('p1'));
console.log(root);
总结: