JavaScript数据结构9——树的存储结构
2017-03-27 本文已影响0人
RichardW
双亲表示法:容易找到父节点,但是很难找到子节点
//树的存储结构
//双亲表示法
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);