首页
视频
资源
登录
原
Js 实现二叉树
4720
人阅读
2020/6/23 14:22
总访问:
2537994
评论:
1
收藏:
0
手机
分类:
前端
![javascript](https://img.tnblog.net/arcimg/hb/5c14989ab3c74f90b440ebd18179410a.jpg) ># Js 实现二叉树 [TOC] <br/> 定义 ------------ <br/> >二叉树是n(n>=0)个节点的有限集合,该集合或者为空集(称为空二叉树),或者由一个根节点和两棵互不相交的、分别称为根节点的左子树和右子树组成。 下列图展示了一棵普通二叉树: ![二叉树](https://img.tnblog.net/arcimg/hb/05c11b15d73342ae8d90d34919662a00.jpg "二叉树") <br/> 二叉树特点 ------------ <br/> >由二叉树定义以及图示分析得出二叉树有以下特点: 1)每个节点最多有两颗子树,所以二叉树中不存在度大于2的节点。 2)左子树和右子树是有顺序的,次序不能任意颠倒。 3)即使树中某节点只有一棵子树,也要区分它是左子树还是右子树。 <br/> 简单代码的实现与运用 ------------ <br/> >### 定义树 <br/> >tree.js ```javascript function Tree(){ this.root=null; } //添加根节点 Tree.prototype.addNode = function(val){ var n = new Node(val); if (this.root == null) { this.root = n; }else{ this.root.addNode(n); } } //执行树的遍历函数 Tree.prototype.traverse = function(){ this.root.visit(); } //查找节点 Tree.prototype.search = function(val){ let SearchOne = this.root.search(val); return SearchOne; } ``` >### 定义节点 <br/> >node.js ```javascript //添加节点 function Node(val) { this.value = val; this.left = null; this.right = null; } //遍历节点 Node.prototype.visit = function(){ if (this.left !=null) { this.left.visit(); } console.log(this.value); if (this.right != null) { this.right.visit(); } } //查找节点 Node.prototype.search = function(val){ if(this.value == val){ return this; }else if(val < this.value && this.left != null){ return this.left.search(val); }else if(val > this.value && this.right != null){ return this.right.search(val); } return null; } //添加子节点 Node.prototype.addNode = function(n){ if(n.value < this.value){ if(this.left==null){ this.left=n; }else{ this.left.addNode(n); } }else if(n.value > this.value){ if(this.right==null){ this.right=n; }else{ this.right.addNode(n); } } } ``` <br/> >### 测试Js的代码 <br/> >sketch.js ```javascript var tree; function setup() { tree = new Tree(); for (var i = 0; i < 10; i++) { tree.addNode(Math.floor(Math.random(0,100)*100)); } console.log(tree); tree.traverse(); } ``` 其他 ------------ <br/> >### 关于二叉树.net扩展 写得不好,大家不要笑哈哈哈哈! Nuget地址:https://www.nuget.org/packages/AiDaSi_BinaryTree/ 项目地址:https://github.com/AiDaShi/GeekTimeLearning/tree/master/BinaryTree
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}
尘叶心繁
这一世以无限游戏为使命!
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
.net后台框架
166篇
linux
17篇
linux中cve
1篇
windows中cve
0篇
资源分享
10篇
Win32
3篇
前端
28篇
传说中的c
4篇
Xamarin
9篇
docker
15篇
容器编排
101篇
grpc
4篇
Go
15篇
yaml模板
1篇
理论
2篇
更多
Sqlserver
4篇
云产品
39篇
git
3篇
Unity
1篇
考证
2篇
RabbitMq
23篇
Harbor
1篇
Ansible
8篇
Jenkins
17篇
Vue
1篇
Ids4
18篇
istio
1篇
架构
2篇
网络
7篇
windbg
4篇
AI
18篇
threejs
2篇
人物
1篇
嵌入式
2篇
python
13篇
HuggingFace
8篇
pytorch
9篇
opencv
6篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术