Skip to content

Commit 36d6ae0

Browse files
author
YuChengKai
committed
BST 实现
1 parent 537e5dd commit 36d6ae0

File tree

2 files changed

+89
-4
lines changed

2 files changed

+89
-4
lines changed

Algorithm/algorithm-ch.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -514,10 +514,10 @@ var traversal = function(root) {
514514
if (root) {
515515
// 先序
516516
console.log(root);
517-
isSymmetric(root.left);
517+
traversal(root.left);
518518
// 中序
519519
// console.log(root);
520-
isSymmetric(root.right);
520+
traversal(root.right);
521521
// 后序
522522
// console.log(root);
523523
}

DataStruct/dataStruct-zh.md

Lines changed: 87 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -261,8 +261,93 @@ class LinkList {
261261

262262
## 二分搜索树
263263

264-
二分搜索树也是二叉树,拥有二叉树的特性。但是区别在于二叉搜索树每个节点的值都比他的左子树的值大,比右子树的值小。
264+
二分搜索树也是二叉树,拥有二叉树的特性。但是区别在于二分搜索树每个节点的值都比他的左子树的值大,比右子树的值小。
265265

266266
这种存储方式很适合于数据搜索。如下图所示,当需要查找 6 的时候,因为需要查找的值比根节点的值大,所以只需要在根节点的右子树上寻找,大大提高了搜索效率。
267267

268-
![](https://user-gold-cdn.xitu.io/2018/5/22/1638850ba7458208?w=596&h=485&f=png&s=36796)
268+
![](https://user-gold-cdn.xitu.io/2018/5/22/1638850ba7458208?w=596&h=485&f=png&s=36796)
269+
270+
### 实现
271+
272+
```js
273+
class Node {
274+
constructor(value) {
275+
this.value = value
276+
this.left = null
277+
this.right = null
278+
}
279+
}
280+
281+
class BST {
282+
constructor() {
283+
this.root = null
284+
this.size = 0
285+
}
286+
getSize() {
287+
return this.size
288+
}
289+
isEmpty() {
290+
return this.size === 0
291+
}
292+
addNode(v) {
293+
this.root = this.addChild(this.root, v)
294+
}
295+
// 添加节点时,需要比较添加的节点值和当前
296+
// 节点值的大小
297+
addChild(node, v) {
298+
if (node.value > v) {
299+
node.left = this.addChild(node.left, v)
300+
} else if (node.value < 0) {
301+
node.right = this.addChild(node.right, v)
302+
}
303+
return node
304+
}
305+
}
306+
```
307+
308+
以上是最基本的二分搜索树实现,接下来实现树的遍历。
309+
310+
对于树的遍历来说,有三种遍历方法,分别是先序遍历、中序遍历、后序遍历。三种遍历的区别在于何时访问节点。在遍历树的过程中,每个节点都会遍历三次,分别是遍历到自己,遍历左子树和遍历右子树。如果需要实现先序遍历,那么只需要第一次遍历到节点时进行操作即可。
311+
312+
```js
313+
// 先序遍历可用于打印树的结构
314+
// 先序遍历表示先访问根节点,然后访问左节点,最后访问右节点。
315+
preTraversal() {
316+
pre(this.root)
317+
}
318+
pre(node) {
319+
if (this.root) {
320+
console.log(this.root.value)
321+
pre(this.root.left)
322+
pre(this.root.right)
323+
}
324+
}
325+
// 中序遍历可用于排序
326+
// 对于 BST 来说,中序遍历可以实现一次遍历就
327+
// 得到有序的值
328+
// 中序遍历表示先访问左节点,然后访问根节点,最后访问右节点。
329+
midTraversal() {
330+
pre(this.root)
331+
}
332+
mid(node) {
333+
if (this.root) {
334+
mid(this.root.left)
335+
console.log(this.root.value)
336+
mid(this.root.right)
337+
}
338+
}
339+
// 后序遍历可用于先操作子节点
340+
// 再操作父节点的场景
341+
// 后序遍历表示先访问左节点,然后访问右节点,最后访问根节点。
342+
backTraversal() {
343+
pre(this.root)
344+
}
345+
back(node) {
346+
if (this.root) {
347+
back(this.root.left)
348+
back(this.root.right)
349+
console.log(this.root.value)
350+
}
351+
}
352+
```
353+

0 commit comments

Comments
 (0)