commit
0ab32d9d0c
@ -0,0 +1,63 @@
|
|||||||
|
//实现二叉树
|
||||||
|
class BinaryTree {
|
||||||
|
constructor(data) {
|
||||||
|
this.data = data;
|
||||||
|
this.left = null;
|
||||||
|
this.right = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BinaryTree.prototype.insert = function(data) {
|
||||||
|
if (data < this.data) {
|
||||||
|
if (this.left === null) {
|
||||||
|
this.left = new BinaryTree(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BinaryTree.prototype.traverse = function(callback) {
|
||||||
|
if (this.left !== null) {
|
||||||
|
this.left.traverse(callback);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 查找树
|
||||||
|
BinaryTree.prototype.find = function(data) {
|
||||||
|
if (this.data === data) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
for (let i = 0; i < this.children.length; i++) {
|
||||||
|
let result = this.children[i].find(data);
|
||||||
|
if (result) {
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// 删除树
|
||||||
|
BinaryTree.prototype.remove = function(data) {
|
||||||
|
for (let i = 0; i < this.children.length; i++) {
|
||||||
|
if (this.children[i].data === data) {
|
||||||
|
this.children.splice(i, 1);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 清空树
|
||||||
|
BinaryTree.prototype.clear = function() {
|
||||||
|
this.children = [];
|
||||||
|
}
|
||||||
|
// 树的高度
|
||||||
|
BinaryTree.prototype.height = function() {
|
||||||
|
let height = 0;
|
||||||
|
}
|
||||||
|
// 树的深度
|
||||||
|
BinaryTree.prototype.depth = function() {
|
||||||
|
let depth = 0;
|
||||||
|
}
|
||||||
|
// 树的大小
|
||||||
|
BinaryTree.prototype.size = function() {
|
||||||
|
let size = 0;
|
||||||
|
}
|
||||||
|
// 树的叶子节点
|
||||||
|
BinaryTree.prototype.leaf = function() {
|
||||||
|
let leaf = 0;
|
||||||
|
}
|
||||||
|
module.exports = BinaryTree;
|
Loading…
Reference in new issue