function createNode(value) {
return {
value,
left: null,
right: null
};
} function BinaryTree(val) {
return {
root: null,
nodes: [],
add(val) {
const node = createNode(val);
if (!this.root) {
this.root = node;
} else {
this.downShift(node);
}
this.nodes.push(node);
},
downShift(node) {
let value = node.value;
let current = this.root;
while (current) {
if (value > current.value) {
if (!current.right) {
current.right = node;
break;
} else {
current = current.right;
}
} else {
if (!current.left) {
current.left = node;
break;
} else {
current = current.left;
}
}
}
},
size() {
return this.nodes.length;
},
search(target) {
let found = false;
let current = this.root;
while (current) {
if (target > current.value) {
if (!current.right) {
return "Not Found";
}
current = current.right;
} else if (target < current.value) {
if (!current.left) {
return "Not Found";
}
current = current.left;
} else {
found = true;
break;
}
}
return found;
}
};
} const t = new BinaryTree();
t.add();
t.add();
t.add();
t.add();
t.add();
t.add();
t.add();
console.log(t.search());

About how to traverse binary tree, can refer this post.

最新文章

  1. iOS开发——高级篇——图片轮播及其无限循环效果
  2. 关于 SSV-ID: 4474 POC的分析和思考
  3. Windows Server 2003 激活码及激活方法
  4. 【BZOJ】【1833】【ZJOI2010】count 数字计数
  5. 对unsigned int和int进行移位操作的区别
  6. 给大家介绍款在线压缩JS的工具
  7. [AngualrJS] Using Angular-Cache for caching http request
  8. python2.x 使用protobuf
  9. git使用系列(一)
  10. 南阳理工oj_The Triangle
  11. Go语言中的make和new
  12. java 接口1
  13. 使用Python计算IP、TCP、UDP校验和
  14. bootstrap-table 中取主键字段的问题,主键名不叫id
  15. Eclipse下,修改MAVEN 中央仓库地址,解决maven下载慢问题
  16. ubuntu学习教程
  17. 维纳滤波和编码曝光PSF去除运动模糊【matlab】
  18. hdu 3715(二分+2-sat)
  19. Careercup - Microsoft面试题 - 5485521224597504
  20. logback 配置详解(下)

热门文章

  1. SQL2:数据操作
  2. SSMdemo:租房管理系统
  3. 【BZOJ 3308】 3308: 九月的咖啡店 (费用流|二分图最大权匹配)
  4. 【最小表示法】BZOJ1398-寻找朋友
  5. mof提权原理及实现
  6. [CodeForces-178F]Representative Sampling
  7. Java并发(九):重入锁 ReentrantLock
  8. bzoj 1030
  9. noip200805笨小猴
  10. 实用在线小工具 -- JS代码压缩工具