Skip to content

Commit bcdc54d

Browse files
author
宋子龙
committed
BST类的root改为Symbol 私有属性
1 parent 4ff2d56 commit bcdc54d

File tree

3 files changed

+17
-20
lines changed

3 files changed

+17
-20
lines changed

.DS_Store

2 KB
Binary file not shown.

BinarySearchTree/binarySearchTree.html

+14-19
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,11 @@
1717
}
1818
}
1919

20+
const root = Symbol('root');
21+
2022
class BinarySearchTree {
2123
constructor() {
22-
this.root = null;
24+
this[root] = null;
2325
}
2426

2527
/** 向二叉树中插入节点
@@ -28,9 +30,9 @@
2830
insert(key) {
2931
const newNode = new Node(key);
3032

31-
this.root
32-
? insertNode(this.root, newNode) // 根节点已存时
33-
: this.root = newNode; // 根节点为空时
33+
this[root]
34+
? insertNode(this[root], newNode) // 根节点已存时
35+
: this[root] = newNode; // 根节点为空时
3436

3537
/** 执行 插入节点 行为的私有函数
3638
* @param {Object} node 二叉树中的节点
@@ -54,7 +56,7 @@
5456
* @param {Function} callback 定义对遍历到的每个节点要进行的操作(Visitor pattern)
5557
*/
5658
inOrderTraverse(callback) {
57-
inOrderTraverseNode(this.root, callback);
59+
inOrderTraverseNode(this[root], callback);
5860

5961
/** 中序遍历的核心代码 (通过递归,从小到大遍历二叉树)
6062
* @param {Object} node 节点
@@ -75,11 +77,8 @@
7577
* @param {Function} callback 定义对遍历到的每个节点要进行的操作(Visitor pattern)
7678
*/
7779
preOrderTraverse(callback) {
78-
preOrderTraverseNode(this.root, callback);
80+
preOrderTraverseNode(this[root], callback);
7981

80-
/**
81-
* @api private
82-
*/
8382
function preOrderTraverseNode(node, callback) {
8483
if (node !== null) {
8584
callback(node.key);
@@ -93,7 +92,7 @@
9392
* @param {Function} callback 定义对遍历到的每个节点要进行的操作(Visitor pattern)
9493
*/
9594
postOrderTraverse(callback) {
96-
postOrderTraverseNode(this.root, callback);
95+
postOrderTraverseNode(this[root], callback);
9796

9897
function postOrderTraverseNode(node, callback) {
9998
if (node !== null) {
@@ -104,22 +103,18 @@
104103
}
105104
}
106105

107-
/**
108-
* @return {Number} 二叉树中的最大值
109-
*/
106+
/** @return {Number} 二叉树中的最大值*/
110107
max() {
111-
let node = this.root || {};
108+
let node = this[root] || {};
112109
while (node.right) {
113110
node = node.right;
114111
}
115112
return node.key;
116113
}
117114

118-
/**
119-
* @return {Number} 二叉树中的最小值
120-
*/
115+
/** @return {Number} 二叉树中的最小值*/
121116
min() {
122-
let node = this.root || {};
117+
let node = this[root] || {};
123118
while (node.left) {
124119
node = node.left;
125120
}
@@ -131,7 +126,7 @@
131126
* @return {Boolean}
132127
*/
133128
search(key) {
134-
return searchNode(this.root, key);
129+
return searchNode(this[root], key);
135130

136131
/**
137132
* @return {Boolean}

sort/quickSort.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,6 @@ function quickSort(arr = []) {
2121
}
2222

2323
return [...quickSort(left), midValue, ...quickSort(right)];
24-
}
24+
}
25+
26+
export default quickSort;

0 commit comments

Comments
 (0)