Skip to content

Commit ce119dc

Browse files
author
YuChengKai
committed
BST Select
1 parent 3f2a179 commit ce119dc

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

DataStruct/dataStruct-zh.md

+43-2
Original file line numberDiff line numberDiff line change
@@ -313,9 +313,11 @@ class BST {
313313

314314
对于树的遍历来说,有三种遍历方法,分别是先序遍历、中序遍历、后序遍历。三种遍历的区别在于何时访问节点。在遍历树的过程中,每个节点都会遍历三次,分别是遍历到自己,遍历左子树和遍历右子树。如果需要实现先序遍历,那么只需要第一次遍历到节点时进行操作即可。
315315

316+
以下都是递归实现,如果你想学习非递归实现,可以 [点击这里阅读](../Algorithm/algorithm-ch.md#%E9%9D%9E%E9%80%92%E5%BD%92%E5%AE%9E%E7%8E%B0)
317+
316318
```js
317319
// 先序遍历可用于打印树的结构
318-
// 先序遍历表示先访问根节点,然后访问左节点,最后访问右节点。
320+
// 先序遍历先访问根节点,然后访问左节点,最后访问右节点。
319321
preTraversal() {
320322
this._pre(this.root)
321323
}
@@ -399,7 +401,6 @@ _getMax(node) {
399401

400402
```js
401403
floor(v) {
402-
if (!this.root) return null
403404
let node = this._floor(this.root, v)
404405
return node ? node.value : null
405406
}
@@ -417,3 +418,43 @@ _floor(node, v) {
417418
}
418419
```
419420

421+
**排名**,这是用于获取给定值的排名或者排名第几的节点的值,这两个操作也是相反的,所以这个只介绍如果获取排名第几的节点的值。对于这个操作而言,我们需要略微的改造点代码,让每个节点拥有一个 `size` 属性。该属性表示该节点下有多少子节点(包含自身)。
422+
423+
```js
424+
class Node {
425+
constructor(value) {
426+
this.value = value
427+
this.left = null
428+
this.right = null
429+
// 修改代码
430+
this.size = 1
431+
}
432+
}
433+
_addChild(node, v) {
434+
if (!node) {
435+
return new Node(v)
436+
}
437+
if (node.value > v) {
438+
// 修改代码
439+
node.size++
440+
node.left = this._addChild(node.left, v)
441+
} else if (node.value < v) {
442+
// 修改代码
443+
node.size++
444+
node.right = this._addChild(node.right, v)
445+
}
446+
return node
447+
}
448+
select(k) {
449+
let node = this._select(this.root, k)
450+
return node ? node.value : null
451+
}
452+
_select(node, k) {
453+
if (!node) return null
454+
let size = node.left ? node.left.size : 0
455+
if (size > k) return this._select(node.left, k)
456+
if (size < k) return this._select(node.right, k - size - 1)
457+
return node
458+
}
459+
```
460+

0 commit comments

Comments
 (0)