JavaScript数据结构9——树的存储结构

双亲表示法:容易找到父节点,但是很难找到子节点

//树的存储结构
//双亲表示法
function PTNode(data) {
    this.data =data;
}
PTNode.prototype.setParent = function(node){
    this.parent = node;
};
function PTree(maxsize,rootNode){
    this.nodes = new Array(maxsize);
    this.rootNode =rootNode;
}
var root = new PTNode(1);
var tree = new PTree(20,root);
var node1 = new PTNode(2);
var node2 = new PTNode(2);
var node3 = new PTNode(2);
var node4 = new PTNode(2);
node1.setParent(root);
node2.setParent(root);
node3.setParent(node1);
node4.setParent(node2);

孩子兄弟表示法,表示一个孩子,和next个兄弟节点

//树的存储结构
//孩子兄弟表示法
function CTNode(data) {
    this.data =data;
}
CTNode.prototype.setChild = function(node){
    this.child = node;
};
CTNode.prototype.setNext = function(node){
    this.next = node;
};
function CTree(maxsize,rootNode){
    this.nodes = new Array(maxsize);
    this.rootNode =rootNode;
}
var root = new CTNode(1);
var tree = new CTree(20,root);
var node1 = new CTNode(2);
var node2 = new CTNode(2);
var node3 = new CTNode(2);
var node4 = new CTNode(2);
root.setChild(node1);
node1.setNext(node2);
node2.setNext(null);
node1.setChild(node3);
node3.setChild(null);
node3.setNext(null);
node2.setChild(node4);
node4.setChild(null);
node4.setNext(null);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容