二叉树 JavaScript实现
时间: 2023-05-11 18:02:11 浏览: 64
二叉树的 JavaScript 实现可以使用对象来表示每个节点,每个节点包含一个值和两个指向左右子节点的指针。以下是一个简单的实现:
```
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
insert(value) {
const node = new Node(value);
if (!this.root) {
this.root = node;
return;
}
let current = this.root;
while (true) {
if (value < current.value) {
if (!current.left) {
current.left = node;
break;
}
current = current.left;
} else {
if (!current.right) {
current.right = node;
break;
}
current = current.right;
}
}
}
search(value) {
let current = this.root;
while (current) {
if (value === current.value) {
return current;
} else if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return null;
}
}
```
你可以使用 `insert` 方法来插入一个值,使用 `search` 方法来查找一个值。例如:
```
const tree = new BinaryTree();
tree.insert(5);
tree.insert(3);
tree.insert(7);
tree.insert(1);
tree.insert(4);
tree.insert(6);
tree.insert(8);
console.log(tree.search(4)); // Node { value: 4, left: Node { value: 1, left: null, right: null }, right: Node { value: 5, left: Node { value: 3, left: null, right: [Node] }, right: Node { value: 7, left: Node { value: 6, left: null, right: null }, right: Node { value: 8, left: null, right: null } } } }
```
这将输出包含值为 4 的节点及其子节点的对象。