标签:function null 实现 javascript right 二叉树 var Btree left
<script type="text/javascript"> //javascript实现属性结构 //相当于用于创建结点 (function(window){ function Btree(str){ this.leftheight = null; this.rightheight = null; this.leftCountNode = null; this.rightCountNode = null; this.ChildNode = null; //保存树的高度 this.height = null; //保存树的结点 this.countNode = null; this.struct = null; //构建树 this.createTree(str); //获取输的信息 this.init(this.struct); }; Btree.prototype = { BtreeNode:function(){ this.left = null; this.right = null; this.data = null; }, createTree:function(str){ var Btree = null;//一个空二叉树 var arr = [];//用一个数组表示栈 var top = 1;//指向栈底 var p = null; var k; Btree = p; var index = 0;//字符串的索引 while(index<str.length){ switch(str[index]){ case '(':arr.push(p),k=1;break; case ',':k=2;break; case ')':arr.pop();break; default: p = new this.BtreeNode(); p.data = str[index]; if(Btree == null){ Btree=p; }else{ switch(k){ case 1:arr[arr.length-1].left = p;break; case 2:arr[arr.length-1].right = p;break; } } ; } index++; } this.struct = Btree; }, init:function(node){ this.getheight(node); this.ChildNode = this.getCountNode(node); }, getheight:function(node){ if(node == null){ return 0; }else{ this.leftheight = this.getheight(node.left); this.rightheight = this.getheight(node.right); return this.height = this.leftheight>this.rightheight?this.leftheight+1:this.rightheight+1; } },//结点个数 getCountNode:function(node){ var left,right; if(node == null){ return 0; }else if(node.left == null && node.right == null){ return 1; }else{ left = this.getCountNode(node.left); right = this.getCountNode(node.right); return (left+right); //注意这里的left不应该使用this.left 或者this.right 这样在递归过程当中会被覆盖掉 } },//显示二叉树 TreeShow:function(Btree,height=0){ //思路先判断该对象是否有左孩子或者右孩子 如果有就递归输出 if(Btree != null){ //首先将当前结点的值输出 Btree.data = Btree.data; var str = ""; for(var i=0;i<height;i++){ str+="--"; } console.log(str + Btree.data); //判断是否还有子节点如果有则继续递归输出 if(Btree.left != null || Btree.right != null){ this.TreeShow(Btree.left,++height); this.TreeShow(Btree.right,height); } } }, TreeAll:function(Btree,height = 0){ //思路先判断该对象是否有左孩子或者右孩子 如果有就递归输出 if(Btree != null){ //首先将当前结点的值输出 Btree.data = Btree.data; var str = ""; for(var i=0;i<height;i++){ str+="--"; } //判断是否还有子节点如果有则继续递归输出 if(Btree.left != null || Btree.right != null){ this.TreeShow(Btree.left,++height); console.log(str + Btree.data); this.TreeShow(Btree.right,height); } } } } window.Btree = Btree; })(window) var str = "1(2(9,3(7,0)),4(6(1,3),8(1,2)))"; var t = new Btree(str); t.TreeShow(t.struct,0); console.log("============="); t.TreeAll(t.struct); </script> </html>
结果
标签:function,null,实现,javascript,right,二叉树,var,Btree,left 来源: https://www.cnblogs.com/webcyh/p/11431914.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。