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