data-structure-typed 1.17.4 → 1.18.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (293) hide show
  1. package/README.md +193 -66
  2. package/backup/recursive-type/src/assets/complexities-diff.jpg +0 -0
  3. package/backup/recursive-type/src/assets/data-structure-complexities.jpg +0 -0
  4. package/backup/recursive-type/src/assets/logo.png +0 -0
  5. package/backup/recursive-type/src/assets/overview-diagram-of-data-structures.png +0 -0
  6. package/backup/recursive-type/src/data-structures/binary-tree/aa-tree.ts +3 -0
  7. package/backup/recursive-type/src/data-structures/binary-tree/avl-tree.ts +288 -0
  8. package/backup/recursive-type/src/data-structures/binary-tree/b-tree.ts +3 -0
  9. package/backup/recursive-type/src/data-structures/binary-tree/binary-indexed-tree.ts +78 -0
  10. package/backup/recursive-type/src/data-structures/binary-tree/binary-tree.ts +1502 -0
  11. package/backup/recursive-type/src/data-structures/binary-tree/bst.ts +503 -0
  12. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/avl-tree-inserting.gif +0 -0
  13. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/bst-rotation.gif +0 -0
  14. package/backup/recursive-type/src/data-structures/binary-tree/diagrams/segment-tree.png +0 -0
  15. package/backup/recursive-type/src/data-structures/binary-tree/index.ts +11 -0
  16. package/backup/recursive-type/src/data-structures/binary-tree/rb-tree.ts +110 -0
  17. package/backup/recursive-type/src/data-structures/binary-tree/segment-tree.ts +243 -0
  18. package/backup/recursive-type/src/data-structures/binary-tree/splay-tree.ts +3 -0
  19. package/backup/recursive-type/src/data-structures/binary-tree/tree-multiset.ts +55 -0
  20. package/backup/recursive-type/src/data-structures/binary-tree/two-three-tree.ts +3 -0
  21. package/backup/recursive-type/src/data-structures/diagrams/README.md +5 -0
  22. package/backup/recursive-type/src/data-structures/graph/abstract-graph.ts +985 -0
  23. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-list-pros-cons.jpg +0 -0
  24. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-list.jpg +0 -0
  25. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-matrix-pros-cons.jpg +0 -0
  26. package/backup/recursive-type/src/data-structures/graph/diagrams/adjacency-matrix.jpg +0 -0
  27. package/backup/recursive-type/src/data-structures/graph/diagrams/dfs-can-do.jpg +0 -0
  28. package/backup/recursive-type/src/data-structures/graph/diagrams/edge-list-pros-cons.jpg +0 -0
  29. package/backup/recursive-type/src/data-structures/graph/diagrams/edge-list.jpg +0 -0
  30. package/backup/recursive-type/src/data-structures/graph/diagrams/max-flow.jpg +0 -0
  31. package/backup/recursive-type/src/data-structures/graph/diagrams/mst.jpg +0 -0
  32. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-articulation-point-bridge.png +0 -0
  33. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-complicate-simple.png +0 -0
  34. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan-strongly-connected-component.png +0 -0
  35. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan.mp4 +0 -0
  36. package/backup/recursive-type/src/data-structures/graph/diagrams/tarjan.webp +0 -0
  37. package/backup/recursive-type/src/data-structures/graph/directed-graph.ts +478 -0
  38. package/backup/recursive-type/src/data-structures/graph/index.ts +3 -0
  39. package/backup/recursive-type/src/data-structures/graph/undirected-graph.ts +293 -0
  40. package/backup/recursive-type/src/data-structures/hash/coordinate-map.ts +67 -0
  41. package/backup/recursive-type/src/data-structures/hash/coordinate-set.ts +56 -0
  42. package/backup/recursive-type/src/data-structures/hash/hash-table.ts +3 -0
  43. package/backup/recursive-type/src/data-structures/hash/index.ts +6 -0
  44. package/backup/recursive-type/src/data-structures/hash/pair.ts +3 -0
  45. package/backup/recursive-type/src/data-structures/hash/tree-map.ts +3 -0
  46. package/backup/recursive-type/src/data-structures/hash/tree-set.ts +3 -0
  47. package/backup/recursive-type/src/data-structures/heap/heap.ts +176 -0
  48. package/backup/recursive-type/src/data-structures/heap/index.ts +3 -0
  49. package/backup/recursive-type/src/data-structures/heap/max-heap.ts +31 -0
  50. package/backup/recursive-type/src/data-structures/heap/min-heap.ts +34 -0
  51. package/backup/recursive-type/src/data-structures/index.ts +15 -0
  52. package/backup/recursive-type/src/data-structures/interfaces/abstract-graph.ts +42 -0
  53. package/backup/recursive-type/src/data-structures/interfaces/avl-tree.ts +1 -0
  54. package/backup/recursive-type/src/data-structures/interfaces/binary-tree.ts +56 -0
  55. package/backup/recursive-type/src/data-structures/interfaces/bst.ts +1 -0
  56. package/backup/recursive-type/src/data-structures/interfaces/directed-graph.ts +15 -0
  57. package/backup/recursive-type/src/data-structures/interfaces/doubly-linked-list.ts +1 -0
  58. package/backup/recursive-type/src/data-structures/interfaces/heap.ts +1 -0
  59. package/backup/recursive-type/src/data-structures/interfaces/index.ts +13 -0
  60. package/backup/recursive-type/src/data-structures/interfaces/navigator.ts +1 -0
  61. package/backup/recursive-type/src/data-structures/interfaces/priority-queue.ts +1 -0
  62. package/backup/recursive-type/src/data-structures/interfaces/segment-tree.ts +1 -0
  63. package/backup/recursive-type/src/data-structures/interfaces/singly-linked-list.ts +1 -0
  64. package/backup/recursive-type/src/data-structures/interfaces/tree-multiset.ts +1 -0
  65. package/backup/recursive-type/src/data-structures/interfaces/undirected-graph.ts +3 -0
  66. package/backup/recursive-type/src/data-structures/linked-list/doubly-linked-list.ts +573 -0
  67. package/backup/recursive-type/src/data-structures/linked-list/index.ts +3 -0
  68. package/backup/recursive-type/src/data-structures/linked-list/singly-linked-list.ts +490 -0
  69. package/backup/recursive-type/src/data-structures/linked-list/skip-linked-list.ts +3 -0
  70. package/backup/recursive-type/src/data-structures/matrix/index.ts +4 -0
  71. package/backup/recursive-type/src/data-structures/matrix/matrix.ts +27 -0
  72. package/backup/recursive-type/src/data-structures/matrix/matrix2d.ts +208 -0
  73. package/backup/recursive-type/src/data-structures/matrix/navigator.ts +122 -0
  74. package/backup/recursive-type/src/data-structures/matrix/vector2d.ts +316 -0
  75. package/backup/recursive-type/src/data-structures/priority-queue/index.ts +3 -0
  76. package/backup/recursive-type/src/data-structures/priority-queue/max-priority-queue.ts +49 -0
  77. package/backup/recursive-type/src/data-structures/priority-queue/min-priority-queue.ts +50 -0
  78. package/backup/recursive-type/src/data-structures/priority-queue/priority-queue.ts +354 -0
  79. package/backup/recursive-type/src/data-structures/queue/deque.ts +251 -0
  80. package/backup/recursive-type/src/data-structures/queue/index.ts +2 -0
  81. package/backup/recursive-type/src/data-structures/queue/queue.ts +120 -0
  82. package/backup/recursive-type/src/data-structures/stack/index.ts +1 -0
  83. package/backup/recursive-type/src/data-structures/stack/stack.ts +98 -0
  84. package/backup/recursive-type/src/data-structures/tree/index.ts +1 -0
  85. package/backup/recursive-type/src/data-structures/tree/tree.ts +80 -0
  86. package/backup/recursive-type/src/data-structures/trie/index.ts +1 -0
  87. package/backup/recursive-type/src/data-structures/trie/trie.ts +227 -0
  88. package/backup/recursive-type/src/data-structures/types/abstract-graph.ts +5 -0
  89. package/backup/recursive-type/src/data-structures/types/avl-tree.ts +8 -0
  90. package/backup/recursive-type/src/data-structures/types/binary-tree.ts +10 -0
  91. package/backup/recursive-type/src/data-structures/types/bst.ts +6 -0
  92. package/backup/recursive-type/src/data-structures/types/directed-graph.ts +8 -0
  93. package/backup/recursive-type/src/data-structures/types/doubly-linked-list.ts +1 -0
  94. package/backup/recursive-type/src/data-structures/types/heap.ts +5 -0
  95. package/backup/recursive-type/src/data-structures/types/index.ts +12 -0
  96. package/backup/recursive-type/src/data-structures/types/navigator.ts +13 -0
  97. package/backup/recursive-type/src/data-structures/types/priority-queue.ts +9 -0
  98. package/backup/recursive-type/src/data-structures/types/segment-tree.ts +1 -0
  99. package/backup/recursive-type/src/data-structures/types/singly-linked-list.ts +1 -0
  100. package/backup/recursive-type/src/data-structures/types/tree-multiset.ts +1 -0
  101. package/backup/recursive-type/src/index.ts +1 -0
  102. package/backup/recursive-type/src/utils/index.ts +2 -0
  103. package/backup/recursive-type/src/utils/types/index.ts +1 -0
  104. package/backup/recursive-type/src/utils/types/utils.ts +6 -0
  105. package/backup/recursive-type/src/utils/utils.ts +78 -0
  106. package/dist/data-structures/binary-tree/avl-tree.d.ts +19 -25
  107. package/dist/data-structures/binary-tree/avl-tree.js +12 -20
  108. package/dist/data-structures/binary-tree/binary-indexed-tree.d.ts +3 -1
  109. package/dist/data-structures/binary-tree/binary-indexed-tree.js +10 -0
  110. package/dist/data-structures/binary-tree/binary-tree.d.ts +135 -161
  111. package/dist/data-structures/binary-tree/binary-tree.js +192 -164
  112. package/dist/data-structures/binary-tree/bst.d.ts +21 -21
  113. package/dist/data-structures/binary-tree/bst.js +33 -36
  114. package/dist/data-structures/binary-tree/rb-tree.d.ts +1 -2
  115. package/dist/data-structures/binary-tree/rb-tree.js +68 -5
  116. package/dist/data-structures/binary-tree/segment-tree.d.ts +17 -39
  117. package/dist/data-structures/binary-tree/segment-tree.js +34 -47
  118. package/dist/data-structures/binary-tree/tree-multiset.d.ts +9 -8
  119. package/dist/data-structures/binary-tree/tree-multiset.js +7 -6
  120. package/dist/data-structures/graph/abstract-graph.d.ts +56 -71
  121. package/dist/data-structures/graph/abstract-graph.js +87 -92
  122. package/dist/data-structures/graph/directed-graph.d.ts +128 -105
  123. package/dist/data-structures/graph/directed-graph.js +161 -121
  124. package/dist/data-structures/graph/undirected-graph.d.ts +81 -62
  125. package/dist/data-structures/graph/undirected-graph.js +99 -78
  126. package/dist/data-structures/hash/coordinate-map.d.ts +1 -5
  127. package/dist/data-structures/hash/coordinate-map.js +3 -9
  128. package/dist/data-structures/hash/coordinate-set.d.ts +2 -6
  129. package/dist/data-structures/hash/coordinate-set.js +3 -9
  130. package/dist/data-structures/hash/hash-table.d.ts +2 -1
  131. package/dist/data-structures/hash/hash-table.js +7 -0
  132. package/dist/data-structures/hash/pair.d.ts +2 -1
  133. package/dist/data-structures/hash/pair.js +7 -0
  134. package/dist/data-structures/hash/tree-map.d.ts +2 -1
  135. package/dist/data-structures/hash/tree-map.js +7 -0
  136. package/dist/data-structures/hash/tree-set.d.ts +2 -1
  137. package/dist/data-structures/hash/tree-set.js +7 -0
  138. package/dist/data-structures/heap/heap.d.ts +0 -14
  139. package/dist/data-structures/heap/heap.js +3 -27
  140. package/dist/data-structures/index.d.ts +1 -0
  141. package/dist/data-structures/index.js +1 -0
  142. package/dist/data-structures/interfaces/abstract-graph.d.ts +22 -0
  143. package/dist/data-structures/interfaces/abstract-graph.js +2 -0
  144. package/dist/data-structures/interfaces/avl-tree.d.ts +1 -0
  145. package/dist/data-structures/interfaces/avl-tree.js +2 -0
  146. package/dist/data-structures/interfaces/binary-tree.d.ts +27 -0
  147. package/dist/data-structures/interfaces/binary-tree.js +2 -0
  148. package/dist/data-structures/interfaces/bst.d.ts +1 -0
  149. package/dist/data-structures/interfaces/bst.js +2 -0
  150. package/dist/data-structures/interfaces/directed-graph.d.ts +9 -0
  151. package/dist/data-structures/interfaces/directed-graph.js +2 -0
  152. package/dist/data-structures/interfaces/doubly-linked-list.d.ts +1 -0
  153. package/dist/data-structures/interfaces/doubly-linked-list.js +2 -0
  154. package/dist/data-structures/interfaces/heap.d.ts +1 -0
  155. package/dist/data-structures/interfaces/heap.js +2 -0
  156. package/dist/data-structures/interfaces/index.d.ts +13 -0
  157. package/dist/data-structures/interfaces/index.js +29 -0
  158. package/dist/data-structures/interfaces/navigator.d.ts +1 -0
  159. package/dist/data-structures/interfaces/navigator.js +2 -0
  160. package/dist/data-structures/interfaces/priority-queue.d.ts +1 -0
  161. package/dist/data-structures/interfaces/priority-queue.js +2 -0
  162. package/dist/data-structures/interfaces/segment-tree.d.ts +1 -0
  163. package/dist/data-structures/interfaces/segment-tree.js +2 -0
  164. package/dist/data-structures/interfaces/singly-linked-list.d.ts +1 -0
  165. package/dist/data-structures/interfaces/singly-linked-list.js +2 -0
  166. package/dist/data-structures/interfaces/tree-multiset.d.ts +1 -0
  167. package/dist/data-structures/interfaces/tree-multiset.js +2 -0
  168. package/dist/data-structures/interfaces/undirected-graph.d.ts +2 -0
  169. package/dist/data-structures/interfaces/undirected-graph.js +2 -0
  170. package/dist/data-structures/linked-list/doubly-linked-list.d.ts +1 -3
  171. package/dist/data-structures/linked-list/doubly-linked-list.js +12 -18
  172. package/dist/data-structures/linked-list/singly-linked-list.d.ts +1 -2
  173. package/dist/data-structures/linked-list/singly-linked-list.js +12 -15
  174. package/dist/data-structures/priority-queue/priority-queue.d.ts +1 -1
  175. package/dist/data-structures/priority-queue/priority-queue.js +4 -4
  176. package/dist/data-structures/queue/deque.d.ts +5 -5
  177. package/dist/data-structures/queue/deque.js +6 -6
  178. package/dist/data-structures/queue/queue.d.ts +1 -1
  179. package/dist/data-structures/stack/stack.d.ts +1 -1
  180. package/dist/data-structures/tree/tree.d.ts +12 -4
  181. package/dist/data-structures/tree/tree.js +44 -12
  182. package/dist/data-structures/trie/trie.d.ts +3 -3
  183. package/dist/data-structures/trie/trie.js +10 -10
  184. package/dist/data-structures/types/abstract-graph.d.ts +1 -20
  185. package/dist/data-structures/types/avl-tree.d.ts +5 -4
  186. package/dist/data-structures/types/binary-tree.d.ts +6 -5
  187. package/dist/data-structures/types/bst.d.ts +4 -3
  188. package/dist/data-structures/types/directed-graph.d.ts +5 -9
  189. package/dist/data-structures/types/directed-graph.js +7 -0
  190. package/dist/data-structures/types/doubly-linked-list.d.ts +1 -1
  191. package/dist/data-structures/types/heap.d.ts +2 -2
  192. package/dist/data-structures/types/index.d.ts +0 -1
  193. package/dist/data-structures/types/index.js +0 -1
  194. package/dist/data-structures/types/navigator.d.ts +2 -2
  195. package/dist/data-structures/types/priority-queue.d.ts +2 -2
  196. package/dist/data-structures/types/tree-multiset.d.ts +3 -4
  197. package/docs/assets/search.js +1 -1
  198. package/docs/classes/AVLTree.html +552 -405
  199. package/docs/classes/AVLTreeNode.html +107 -242
  200. package/docs/classes/AaTree.html +18 -13
  201. package/docs/classes/AbstractEdge.html +77 -68
  202. package/docs/classes/AbstractGraph.html +223 -115
  203. package/docs/classes/AbstractVertex.html +71 -45
  204. package/docs/classes/ArrayDeque.html +31 -26
  205. package/docs/classes/BST.html +543 -391
  206. package/docs/classes/BSTNode.html +107 -236
  207. package/docs/classes/BTree.html +18 -13
  208. package/docs/classes/BinaryIndexedTree.html +56 -21
  209. package/docs/classes/BinaryTree.html +564 -355
  210. package/docs/classes/BinaryTreeNode.html +146 -199
  211. package/docs/classes/Character.html +21 -16
  212. package/docs/classes/CoordinateMap.html +49 -52
  213. package/docs/classes/CoordinateSet.html +50 -53
  214. package/docs/classes/Deque.html +51 -68
  215. package/docs/classes/DirectedEdge.html +98 -103
  216. package/docs/classes/DirectedGraph.html +449 -210
  217. package/docs/classes/DirectedVertex.html +63 -52
  218. package/docs/classes/DoublyLinkedList.html +56 -71
  219. package/docs/classes/DoublyLinkedListNode.html +28 -23
  220. package/docs/classes/HashTable.html +155 -0
  221. package/docs/classes/Heap.html +33 -109
  222. package/docs/classes/HeapItem.html +25 -20
  223. package/docs/classes/Matrix2D.html +33 -28
  224. package/docs/classes/MatrixNTI2D.html +21 -16
  225. package/docs/classes/MaxHeap.html +33 -114
  226. package/docs/classes/MaxPriorityQueue.html +71 -61
  227. package/docs/classes/MinHeap.html +33 -114
  228. package/docs/classes/MinPriorityQueue.html +71 -61
  229. package/docs/classes/Navigator.html +28 -23
  230. package/docs/classes/ObjectDeque.html +66 -51
  231. package/docs/classes/{RBTree.html → Pair.html} +25 -20
  232. package/docs/classes/PriorityQueue.html +66 -56
  233. package/docs/classes/Queue.html +33 -28
  234. package/docs/classes/SegmentTree.html +129 -57
  235. package/docs/classes/SegmentTreeNode.html +62 -140
  236. package/docs/classes/SinglyLinkedList.html +53 -58
  237. package/docs/classes/SinglyLinkedListNode.html +25 -20
  238. package/docs/classes/SkipLinkedList.html +18 -13
  239. package/docs/classes/SplayTree.html +18 -13
  240. package/docs/classes/Stack.html +31 -26
  241. package/docs/classes/TreeMap.html +155 -0
  242. package/docs/classes/TreeMultiSet.html +541 -388
  243. package/docs/classes/TreeNode.html +125 -35
  244. package/docs/classes/TreeSet.html +155 -0
  245. package/docs/classes/Trie.html +30 -25
  246. package/docs/classes/TrieNode.html +33 -28
  247. package/docs/classes/TwoThreeTree.html +18 -13
  248. package/docs/classes/UndirectedEdge.html +87 -80
  249. package/docs/classes/UndirectedGraph.html +356 -178
  250. package/docs/classes/UndirectedVertex.html +63 -52
  251. package/docs/classes/Vector2D.html +45 -40
  252. package/docs/enums/CP.html +21 -16
  253. package/docs/enums/FamilyPosition.html +21 -16
  254. package/docs/enums/LoopType.html +20 -15
  255. package/docs/{interfaces/AVLTreeDeleted.html → enums/TopologicalProperty.html} +47 -44
  256. package/docs/index.html +203 -69
  257. package/docs/interfaces/{PriorityQueueOptions.html → IBinaryTree.html} +49 -40
  258. package/docs/interfaces/IBinaryTreeNode.html +383 -0
  259. package/docs/interfaces/IDirectedGraph.html +24 -19
  260. package/docs/interfaces/IGraph.html +122 -89
  261. package/docs/interfaces/{HeapOptions.html → IUNDirectedGraph.html} +26 -53
  262. package/docs/modules.html +33 -23
  263. package/docs/types/{ToThunkFn.html → AVLTreeDeleted.html} +31 -22
  264. package/docs/types/BSTComparator.html +18 -13
  265. package/docs/types/BSTDeletedResult.html +23 -18
  266. package/docs/types/BinaryTreeDeleted.html +23 -18
  267. package/docs/types/BinaryTreeNodeId.html +18 -13
  268. package/docs/types/BinaryTreeNodePropertyName.html +18 -13
  269. package/docs/types/DFSOrderPattern.html +18 -13
  270. package/docs/types/DijkstraResult.html +18 -13
  271. package/docs/types/Direction.html +18 -13
  272. package/docs/types/{DoublyLinkedListGetBy.html → EdgeId.html} +22 -17
  273. package/docs/types/{TrlFn.html → HeapOptions.html} +33 -20
  274. package/docs/types/{TrlAsyncFn.html → NavigatorParams.html} +46 -20
  275. package/docs/types/NodeOrPropertyName.html +18 -13
  276. package/docs/types/PriorityQueueComparator.html +18 -13
  277. package/docs/types/PriorityQueueDFSOrderPattern.html +18 -13
  278. package/docs/types/{SpecifyOptional.html → PriorityQueueOptions.html} +32 -20
  279. package/docs/types/RecursiveAVLTreeNode.html +135 -0
  280. package/docs/types/RecursiveBSTNode.html +135 -0
  281. package/docs/types/RecursiveBinaryTreeNode.html +135 -0
  282. package/docs/types/ResultByProperty.html +21 -16
  283. package/docs/types/ResultsByProperty.html +21 -16
  284. package/docs/types/SegmentTreeNodeVal.html +18 -13
  285. package/docs/types/TopologicalStatus.html +18 -13
  286. package/docs/types/TreeMultiSetDeletedResult.html +23 -18
  287. package/docs/types/Turning.html +18 -13
  288. package/docs/types/VertexId.html +18 -13
  289. package/notes/note.md +12 -1
  290. package/package.json +11 -3
  291. package/tsconfig.json +2 -2
  292. package/docs/interfaces/NavigatorParams.html +0 -197
  293. package/docs/types/Thunk.html +0 -133
@@ -0,0 +1,1502 @@
1
+ /**
2
+ * data-structure-typed
3
+ *
4
+ * @author Tyler Zeng
5
+ * @copyright Copyright (c) 2022 Tyler Zeng <zrwusa@gmail.com>
6
+ * @license MIT License
7
+ */
8
+
9
+ import {trampoline} from '../../utils';
10
+ import type {
11
+ BinaryTreeDeleted,
12
+ BinaryTreeNodeId,
13
+ BinaryTreeNodePropertyName,
14
+ DFSOrderPattern,
15
+ NodeOrPropertyName, RecursiveBinaryTreeNode,
16
+ ResultByProperty,
17
+ ResultsByProperty
18
+ } from '../types';
19
+ import {IBinaryTree, IBinaryTreeNode} from '../interfaces';
20
+
21
+ /* This enumeration defines the position of a node within a family tree composed of three associated nodes, where 'root' represents the root node of the family tree, 'left' represents the left child node, and 'right' represents the right child node. */
22
+ export enum FamilyPosition {root, left, right}
23
+
24
+ /**
25
+ * Enum representing different loop types.
26
+ *
27
+ * - `iterative`: Indicates the iterative loop type (with loops that use iterations).
28
+ * - `recursive`: Indicates the recursive loop type (with loops that call themselves).
29
+ */
30
+ export enum LoopType { iterative = 1, recursive = 2}
31
+
32
+ export class BinaryTreeNode<T, FAMILY extends BinaryTreeNode<T, FAMILY> = RecursiveBinaryTreeNode<T>> implements IBinaryTreeNode<T, FAMILY> {
33
+
34
+ constructor(id: BinaryTreeNodeId, val: T, count?: number) {
35
+ this._id = id;
36
+ this._val = val;
37
+ this._count = count ?? 1;
38
+ }
39
+
40
+ private _id: BinaryTreeNodeId;
41
+
42
+ get id(): BinaryTreeNodeId {
43
+ return this._id;
44
+ }
45
+
46
+ set id(v: BinaryTreeNodeId) {
47
+ this._id = v;
48
+ }
49
+
50
+ private _val: T;
51
+
52
+ get val(): T {
53
+ return this._val;
54
+ }
55
+
56
+ set val(v: T) {
57
+ this._val = v;
58
+ }
59
+
60
+ private _left?: FAMILY | null;
61
+
62
+ get left(): FAMILY | null | undefined {
63
+ return this._left;
64
+ }
65
+
66
+ set left(v: FAMILY | null | undefined) {
67
+ if (v) {
68
+ v.parent = this as unknown as FAMILY;
69
+ v.familyPosition = FamilyPosition.left;
70
+ }
71
+ this._left = v;
72
+ }
73
+
74
+ private _right?: FAMILY | null;
75
+
76
+ get right(): FAMILY | null | undefined {
77
+ return this._right;
78
+ }
79
+
80
+ set right(v: FAMILY | null | undefined) {
81
+ if (v) {
82
+ v.parent = this as unknown as FAMILY;
83
+ v.familyPosition = FamilyPosition.right;
84
+ }
85
+ this._right = v;
86
+ }
87
+
88
+ private _parent: FAMILY | null | undefined;
89
+
90
+ get parent(): FAMILY | null | undefined {
91
+ return this._parent;
92
+ }
93
+
94
+ set parent(v: FAMILY | null | undefined) {
95
+ this._parent = v;
96
+ }
97
+
98
+ private _familyPosition: FamilyPosition = FamilyPosition.root;
99
+
100
+ get familyPosition(): FamilyPosition {
101
+ return this._familyPosition;
102
+ }
103
+
104
+ set familyPosition(v: FamilyPosition) {
105
+ this._familyPosition = v;
106
+ }
107
+
108
+ private _count = 1;
109
+
110
+ get count(): number {
111
+ return this._count;
112
+ }
113
+
114
+ set count(v: number) {
115
+ this._count = v;
116
+ }
117
+
118
+ private _height = 0;
119
+
120
+ get height(): number {
121
+ return this._height;
122
+ }
123
+
124
+ set height(v: number) {
125
+ this._height = v;
126
+ }
127
+
128
+ _createNode(id: BinaryTreeNodeId, val: T | null, count?: number): FAMILY | null {
129
+ return val !== null ? new BinaryTreeNode<T, FAMILY>(id, val, count) as FAMILY : null;
130
+ }
131
+
132
+ swapLocation(swapNode: FAMILY): FAMILY {
133
+ const {val, count, height} = swapNode;
134
+ const tempNode = this._createNode(swapNode.id, val);
135
+ if (tempNode instanceof BinaryTreeNode) {
136
+ tempNode.val = val;
137
+ tempNode.count = count;
138
+ tempNode.height = height;
139
+
140
+ swapNode.id = this.id;
141
+ swapNode.val = this.val;
142
+ swapNode.count = this.count;
143
+ swapNode.height = this.height;
144
+
145
+ this.id = tempNode.id;
146
+ this.val = tempNode.val;
147
+ this.count = tempNode.count;
148
+ this.height = tempNode.height;
149
+ }
150
+ return swapNode;
151
+ }
152
+
153
+ clone(): FAMILY | null {
154
+ return this._createNode(this.id, this.val, this.count);
155
+ }
156
+ }
157
+
158
+ export class BinaryTree<N extends BinaryTreeNode<N['val'], N> = BinaryTreeNode<number>> implements IBinaryTree<N> {
159
+
160
+ /**
161
+ * The constructor function accepts an optional options object and sets the values of loopType, autoIncrementId, and
162
+ * isDuplicatedVal based on the provided options.
163
+ * @param [options] - An optional object that can contain the following properties:
164
+ */
165
+ constructor(options?: {
166
+ loopType?: LoopType,
167
+ autoIncrementId?: boolean,
168
+ isDuplicatedVal?: boolean
169
+ }) {
170
+ if (options !== undefined) {
171
+ const {
172
+ loopType = LoopType.iterative,
173
+ autoIncrementId = false,
174
+ isDuplicatedVal = false
175
+ } = options;
176
+ this._isDuplicatedVal = isDuplicatedVal;
177
+ this._autoIncrementId = autoIncrementId;
178
+ this._loopType = loopType;
179
+ }
180
+ }
181
+
182
+ private _loopType: LoopType = LoopType.iterative;
183
+
184
+ get loopType(): LoopType {
185
+ return this._loopType;
186
+ }
187
+
188
+ private _visitedId: BinaryTreeNodeId[] = [];
189
+ get visitedId(): BinaryTreeNodeId[] {
190
+ return this._visitedId;
191
+ }
192
+
193
+ private _visitedVal: Array<N['val']> = [];
194
+
195
+ get visitedVal(): Array<N['val']> {
196
+ return this._visitedVal;
197
+ }
198
+
199
+ private _visitedNode: N[] = [];
200
+
201
+ get visitedNode(): N[] {
202
+ return this._visitedNode;
203
+ }
204
+
205
+ private _visitedCount: number[] = [];
206
+
207
+ get visitedCount(): number[] {
208
+ return this._visitedCount;
209
+ }
210
+
211
+ private _visitedLeftSum: number[] = [];
212
+
213
+ get visitedLeftSum(): number[] {
214
+ return this._visitedLeftSum;
215
+ }
216
+
217
+ private _autoIncrementId: boolean = false;
218
+
219
+ get autoIncrementId(): boolean {
220
+ return this._autoIncrementId;
221
+ }
222
+
223
+ private _maxId: number = -1;
224
+
225
+ get maxId(): number {
226
+ return this._maxId;
227
+ }
228
+
229
+ private _isDuplicatedVal: boolean = false;
230
+
231
+ get isDuplicatedVal(): boolean {
232
+ return this._isDuplicatedVal;
233
+ }
234
+
235
+ private _root: N | null = null;
236
+
237
+ get root(): N | null {
238
+ return this._root;
239
+ }
240
+
241
+ private _size = 0;
242
+
243
+ get size(): number {
244
+ return this._size;
245
+ }
246
+
247
+ private _count = 0;
248
+
249
+ get count(): number {
250
+ return this._count;
251
+ }
252
+
253
+ /**
254
+ * The function creates a new binary tree node with the given id, value, and count if the value is not null, otherwise
255
+ * it returns null.
256
+ * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier for the binary tree node. It is of type
257
+ * `BinaryTreeNodeId`.
258
+ * @param {N | null} val - The `val` parameter represents the value of the node. It can be of type `N` (generic type)
259
+ * or `null`.
260
+ * @param {number} [count] - The `count` parameter is an optional parameter of type `number`. It represents the number
261
+ * of occurrences of the value in the binary tree node. If not provided, the default value is `undefined`.
262
+ * @returns a BinaryTreeNode object if the value is not null, otherwise it returns null.
263
+ */
264
+ _createNode(id: BinaryTreeNodeId, val: N['val'] | null, count?: number): N | null {
265
+ const node = new BinaryTreeNode<N['val'], N>(id, val, count);
266
+ return node as N | null;
267
+ }
268
+
269
+ /**
270
+ * The clear function resets the state of an object by setting its properties to their initial values.
271
+ */
272
+ clear() {
273
+ this._setRoot(null);
274
+ this._setSize(0);
275
+ this._setCount(0);
276
+ this._setMaxId(-1);
277
+ }
278
+
279
+ /**
280
+ * The function checks if the size of an object is equal to zero and returns a boolean value.
281
+ * @returns A boolean value indicating whether the size of the object is 0 or not.
282
+ */
283
+ isEmpty(): boolean {
284
+ return this.size === 0;
285
+ }
286
+
287
+ /**
288
+ * The `add` function inserts a new node with a given ID and value into a binary tree, updating the count if the node
289
+ * already exists.
290
+ * @param {BinaryTreeNodeId} id - The id parameter is the identifier of the binary tree node. It is used to uniquely
291
+ * identify each node in the binary tree.
292
+ * @param {N} val - The value to be inserted into the binary tree.
293
+ * @param {number} [count] - The `count` parameter is an optional parameter that specifies the number of times the
294
+ * value should be inserted into the binary tree. If not provided, it defaults to 1.
295
+ * @returns The function `add` returns a `N` object if a new node is inserted, or `null` if no new node
296
+ * is inserted, or `undefined` if the insertion fails.
297
+ */
298
+ add(id: BinaryTreeNodeId, val: N['val'], count?: number): N | null | undefined {
299
+ count = count ?? 1;
300
+
301
+ const _bfs = (root: N, newNode: N | null): N | undefined | null => {
302
+ const queue: Array<N | null> = [root];
303
+ while (queue.length > 0) {
304
+ const cur = queue.shift();
305
+ if (cur) {
306
+ const inserted = this.addTo(newNode, cur);
307
+ if (inserted !== undefined) return inserted;
308
+ if (cur.left) queue.push(cur.left);
309
+ if (cur.right) queue.push(cur.right);
310
+ } else return;
311
+ }
312
+ return;
313
+ };
314
+
315
+ let inserted: N | null | undefined;
316
+ const needInsert = val !== null ? this._createNode(id, val, count) : null;
317
+ const existNode = val !== null ? this.get(id, 'id') : null;
318
+ if (this.root) {
319
+ if (existNode) {
320
+ existNode.count += count;
321
+ existNode.val = val;
322
+ if (needInsert !== null) {
323
+ this._setCount(this.count + count);
324
+ inserted = existNode;
325
+ }
326
+ } else {
327
+ inserted = _bfs(this.root, needInsert);
328
+ }
329
+ } else {
330
+ this._setRoot(val !== null ? this._createNode(id, val, count) : null);
331
+ if (needInsert !== null) {
332
+ this._setSize(1);
333
+ this._setCount(count);
334
+ }
335
+ inserted = this.root;
336
+ }
337
+ return inserted;
338
+ }
339
+
340
+ /**
341
+ * The function inserts a new node into a binary tree as the left or right child of a given parent node.
342
+ * @param {N | null} newNode - The `newNode` parameter is an instance of the `BinaryTreeNode` class or
343
+ * `null`. It represents the node that needs to be inserted into the binary tree.
344
+ * @param parent - The `parent` parameter is a BinaryTreeNode object representing the parent node to which the new node
345
+ * will be inserted as a child.
346
+ * @returns The method returns the newly inserted node, either as the left child or the right child of the parent node.
347
+ */
348
+ addTo(newNode: N | null, parent: N) {
349
+ if (parent) {
350
+ if (parent.left === undefined) {
351
+ if (newNode) {
352
+ newNode.parent = parent;
353
+ newNode.familyPosition = FamilyPosition.left;
354
+ }
355
+ parent.left = newNode;
356
+ if (newNode !== null) {
357
+ this._setSize(this.size + 1);
358
+ this._setCount(this.count + newNode.count ?? 0)
359
+ }
360
+
361
+ return parent.left;
362
+ } else if (parent.right === undefined) {
363
+ if (newNode) {
364
+ newNode.parent = parent;
365
+ newNode.familyPosition = FamilyPosition.right;
366
+ }
367
+ parent.right = newNode;
368
+ if (newNode !== null) {
369
+ this._setSize(this.size + 1);
370
+ this._setCount(this.count + newNode.count ?? 0);
371
+ }
372
+ return parent.right;
373
+ } else {
374
+ return;
375
+ }
376
+ } else {
377
+ return;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * The `addMany` function inserts multiple items into a binary tree and returns an array of the inserted nodes or
383
+ * null/undefined values.
384
+ * @param {N[] | N[]} data - The `data` parameter can be either an array of elements of type `N` or an
385
+ * array of `N` objects.
386
+ * @returns The function `addMany` returns an array of `N`, `null`, or `undefined` values.
387
+ */
388
+ addMany(data: N[] | Array<N['val']>): (N | null | undefined)[] {
389
+ const inserted: (N | null | undefined)[] = [];
390
+ const map: Map<N | N['val'], number> = new Map();
391
+
392
+ if (!this._isDuplicatedVal) {
393
+ for (const i of data) map.set(i, (map.get(i) ?? 0) + 1);
394
+ }
395
+
396
+ for (const item of data) {
397
+ const count = this._isDuplicatedVal ? 1 : map.get(item);
398
+
399
+ if (item instanceof BinaryTreeNode) {
400
+ inserted.push(this.add(item.id, item.val, item.count));
401
+ } else if (typeof item === 'number' && !this._autoIncrementId) {
402
+ if (!this._isDuplicatedVal) {
403
+ if (map.get(item) !== undefined) {
404
+ inserted.push(this.add(item, item, count));
405
+ map.delete(item);
406
+ }
407
+ } else {
408
+ inserted.push(this.add(item, item, 1));
409
+ }
410
+ } else {
411
+ if (item !== null) {
412
+ if (!this._isDuplicatedVal) {
413
+ if (map.get(item) !== undefined) {
414
+ inserted.push(this.add(++this._maxId, item, count));
415
+ map.delete(item);
416
+ }
417
+ } else {
418
+ inserted.push(this.add(++this._maxId, item, 1));
419
+ }
420
+ } else {
421
+ inserted.push(this.add(Number.MAX_SAFE_INTEGER, item, 0));
422
+ }
423
+ }
424
+ }
425
+ return inserted;
426
+ }
427
+
428
+ /**
429
+ * The `fill` function clears the current data and inserts new data, returning a boolean indicating if the insertion
430
+ * was successful.
431
+ * @param {N[] | N[]} data - The `data` parameter can be either an array of elements of type `N` or an
432
+ * array of `N` objects.
433
+ * @returns The method is returning a boolean value.
434
+ */
435
+ fill(data: N[] | N[]): boolean {
436
+ this.clear();
437
+ return data.length === this.addMany(data).length;
438
+ }
439
+
440
+ /**
441
+ * The function removes a node from a binary tree and returns information about the deleted node.
442
+ * @param {BinaryTreeNodeId} id - The `id` parameter is the identifier of the binary tree node that you want to remove.
443
+ * It is of type `BinaryTreeNodeId`.
444
+ * @param {boolean} [ignoreCount] - The `ignoreCount` parameter is an optional boolean parameter that determines
445
+ * whether to ignore the count of the node being removed. If `ignoreCount` is set to `true`, the count of the node will
446
+ * not be decremented and the overall count of the binary tree will not be updated. If `
447
+ * @returns An array of objects is being returned. Each object in the array has two properties: "deleted" and
448
+ * "needBalanced". The "deleted" property contains the deleted node or undefined if no node was deleted. The
449
+ * "needBalanced" property is always null.
450
+ */
451
+ remove(id: BinaryTreeNodeId, ignoreCount?: boolean): BinaryTreeDeleted<N>[] {
452
+ const nodes = this.getNodes(id, 'id', true);
453
+ let node: N | null | undefined = nodes[0];
454
+
455
+ if (!node) node = undefined;
456
+ else if (node.count > 1 && !ignoreCount) {
457
+ node.count--;
458
+ this._setCount(this.count - 1);
459
+ } else if (node instanceof BinaryTreeNode) {
460
+ const [subSize, subCount] = this.getSubTreeSizeAndCount(node);
461
+
462
+ switch (node.familyPosition) {
463
+ case 0:
464
+ this._setSize(this.size - subSize);
465
+ this._setCount(this.count - subCount);
466
+ node = undefined;
467
+ break;
468
+ case 1:
469
+ if (node.parent) {
470
+ this._setSize(this.size - subSize);
471
+ this._setCount(this.count - subCount);
472
+ node.parent.left = null;
473
+ }
474
+ break;
475
+ case 2:
476
+ if (node.parent) {
477
+ this._setSize(this.size - subSize);
478
+ this._setCount(this.count - subCount);
479
+ node.parent.right = null;
480
+ }
481
+ break;
482
+ }
483
+ }
484
+ return [{deleted: node, needBalanced: null}];
485
+ }
486
+
487
+ /**
488
+ * The function calculates the depth of a binary tree node by traversing its parent nodes.
489
+ * @param node - N - This is the node for which we want to calculate the depth. It is a generic type,
490
+ * meaning it can represent any type of data that we want to store in the node.
491
+ * @returns The depth of the given binary tree node.
492
+ */
493
+ getDepth(node: N): number {
494
+ let depth = 0;
495
+ while (node.parent) {
496
+ depth++;
497
+ node = node.parent;
498
+ }
499
+ return depth;
500
+ }
501
+
502
+ /**
503
+ * The `getHeight` function calculates the maximum height of a binary tree using either a recursive or iterative
504
+ * approach.
505
+ * @param {N | null} [beginRoot] - The `beginRoot` parameter is an optional parameter of type
506
+ * `N | null`. It represents the starting node from which to calculate the height of the binary tree.
507
+ * If no value is provided for `beginRoot`, the function will use the `root` property of the class instance as
508
+ * @returns the height of the binary tree.
509
+ */
510
+ getHeight(beginRoot?: N | null): number {
511
+ beginRoot = beginRoot ?? this.root;
512
+ if (!beginRoot) return -1;
513
+
514
+ if (this._loopType === LoopType.recursive) {
515
+ const _getMaxHeight = (cur: N | null | undefined): number => {
516
+ if (!cur) return -1;
517
+ const leftHeight = _getMaxHeight(cur.left);
518
+ const rightHeight = _getMaxHeight(cur.right);
519
+ return Math.max(leftHeight, rightHeight) + 1;
520
+ };
521
+
522
+ return _getMaxHeight(beginRoot);
523
+ } else {
524
+ const stack: N[] = [];
525
+ let node: N | null | undefined = beginRoot, last: N | null = null;
526
+ const depths: Map<N, number> = new Map();
527
+
528
+ while (stack.length > 0 || node) {
529
+ if (node) {
530
+ stack.push(node);
531
+ node = node.left;
532
+ } else {
533
+ node = stack[stack.length - 1]
534
+ if (!node.right || last === node.right) {
535
+ node = stack.pop();
536
+ if (node) {
537
+ const leftHeight = node.left ? depths.get(node.left) ?? -1 : -1;
538
+ const rightHeight = node.right ? depths.get(node.right) ?? -1 : -1;
539
+ depths.set(node, 1 + Math.max(leftHeight, rightHeight));
540
+ last = node;
541
+ node = null;
542
+ }
543
+ } else node = node.right
544
+ }
545
+ }
546
+
547
+ return depths.get(beginRoot) ?? -1;
548
+ }
549
+ }
550
+
551
+ /**
552
+ * The `getMinHeight` function calculates the minimum height of a binary tree using either a recursive or iterative
553
+ * approach.
554
+ * @param {N | null} [beginRoot] - The `beginRoot` parameter is an optional parameter of type
555
+ * `N | null`. It represents the starting node from which to calculate the minimum height of the binary
556
+ * tree. If no value is provided for `beginRoot`, the function will use the root node of the binary tree.
557
+ * @returns The function `getMinHeight` returns the minimum height of the binary tree.
558
+ */
559
+ getMinHeight(beginRoot?: N | null): number {
560
+ beginRoot = beginRoot || this.root;
561
+ if (!beginRoot) return -1;
562
+
563
+ if (this._loopType === LoopType.recursive) {
564
+ const _getMinHeight = (cur: N | null | undefined): number => {
565
+ if (!cur) return 0;
566
+ if (!cur.left && !cur.right) return 0;
567
+ const leftMinHeight = _getMinHeight(cur.left);
568
+ const rightMinHeight = _getMinHeight(cur.right);
569
+ return Math.min(leftMinHeight, rightMinHeight) + 1;
570
+ };
571
+
572
+ return _getMinHeight(beginRoot);
573
+ } else {
574
+ const stack: N[] = [];
575
+ let node: N | null | undefined = beginRoot, last: N | null = null;
576
+ const depths: Map<N, number> = new Map();
577
+
578
+ while (stack.length > 0 || node) {
579
+ if (node) {
580
+ stack.push(node);
581
+ node = node.left;
582
+ } else {
583
+ node = stack[stack.length - 1]
584
+ if (!node.right || last === node.right) {
585
+ node = stack.pop();
586
+ if (node) {
587
+ const leftMinHeight = node.left ? depths.get(node.left) ?? -1 : -1;
588
+ const rightMinHeight = node.right ? depths.get(node.right) ?? -1 : -1;
589
+ depths.set(node, 1 + Math.min(leftMinHeight, rightMinHeight));
590
+ last = node;
591
+ node = null;
592
+ }
593
+ } else node = node.right
594
+ }
595
+ }
596
+
597
+ return depths.get(beginRoot) ?? -1;
598
+ }
599
+ }
600
+
601
+ /**
602
+ * The function checks if a binary tree is balanced by comparing the minimum height and the maximum height of the tree.
603
+ * @param {N | null} [beginRoot] - The `beginRoot` parameter is the root node of a binary tree. It is
604
+ * of type `N | null`, which means it can either be a `BinaryTreeNode` object or `null`.
605
+ * @returns The method is returning a boolean value.
606
+ */
607
+ isBalanced(beginRoot?: N | null): boolean {
608
+ return (this.getMinHeight(beginRoot) + 1 >= this.getHeight(beginRoot));
609
+ }
610
+
611
+ /**
612
+ * The function `getNodes` returns an array of binary tree nodes that match a given property value, with options for
613
+ * searching recursively or iteratively.
614
+ * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
615
+ * generic type `N`. It represents the property of the binary tree node that you want to search for.
616
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
617
+ * specifies the property name to use when searching for nodes. If not provided, it defaults to 'id'.
618
+ * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
619
+ * return only one node that matches the `nodeProperty` or `propertyName` criteria. If `onlyOne` is set to `true`, the
620
+ * function will stop traversing the tree and return the first matching node. If `
621
+ * @returns The function `getNodes` returns an array of `N | null | undefined` objects.
622
+ */
623
+ getNodes(nodeProperty: BinaryTreeNodeId | N, propertyName ?: BinaryTreeNodePropertyName, onlyOne ?: boolean) {
624
+ if (!this.root) return [] as null[];
625
+ propertyName = propertyName ?? 'id';
626
+
627
+ const result: (N | null | undefined)[] = [];
628
+
629
+ if (this._loopType === LoopType.recursive) {
630
+ const _traverse = (cur: N) => {
631
+ if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return;
632
+ if (!cur.left && !cur.right) return;
633
+ cur.left && _traverse(cur.left);
634
+ cur.right && _traverse(cur.right);
635
+ }
636
+
637
+ _traverse(this.root);
638
+ } else {
639
+ const queue: N[] = [this.root];
640
+ while (queue.length > 0) {
641
+ const cur = queue.shift();
642
+ if (cur) {
643
+ if (this._pushByPropertyNameStopOrNot(cur, result, nodeProperty, propertyName, onlyOne)) return result;
644
+ cur.left && queue.push(cur.left);
645
+ cur.right && queue.push(cur.right);
646
+ }
647
+ }
648
+ }
649
+
650
+ return result;
651
+ }
652
+
653
+ /**
654
+ * The function checks if a binary tree node has a specific property or if any node in the tree has a specific
655
+ * property.
656
+ * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
657
+ * generic type `N`. It represents the property of a binary tree node that you want to check.
658
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
659
+ * specifies the name of the property to check for in the nodes.
660
+ * @returns a boolean value.
661
+ */
662
+ has(nodeProperty: BinaryTreeNodeId | N, propertyName ?: BinaryTreeNodePropertyName): boolean {
663
+ return this.getNodes(nodeProperty, propertyName).length > 0;
664
+ }
665
+
666
+ /**
667
+ * The function returns the first binary tree node that matches the given property name and value, or null if no match
668
+ * is found.
669
+ * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter can be either a `BinaryTreeNodeId` or a
670
+ * generic type `N`. It represents the property of the binary tree node that you want to search for.
671
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
672
+ * specifies the property of the binary tree node to search for. If not provided, it defaults to `'id'`.
673
+ * @returns a BinaryTreeNode object or null.
674
+ */
675
+ get(nodeProperty: BinaryTreeNodeId | N, propertyName ?: BinaryTreeNodePropertyName): N | null {
676
+ propertyName = propertyName ?? 'id';
677
+ return this.getNodes(nodeProperty, propertyName, true)[0] ?? null;
678
+ }
679
+
680
+ /**
681
+ * The function getPathToRoot returns an array of BinaryTreeNode objects representing the path from a given node to the
682
+ * root of a binary tree.
683
+ * @param node - The `node` parameter is a BinaryTreeNode object.
684
+ * @returns The function `getPathToRoot` returns an array of `N` objects, representing the path from
685
+ * the given `node` to the root of the binary tree.
686
+ */
687
+ getPathToRoot(node: N): N[] {
688
+ const result: N[] = [];
689
+ while (node.parent) {
690
+ result.unshift(node);
691
+ node = node.parent;
692
+ }
693
+ result.unshift(node);
694
+ return result;
695
+ }
696
+
697
+ getLeftMost(): N | null;
698
+
699
+ getLeftMost(node: N): N;
700
+
701
+ /**
702
+ * The `getLeftMost` function returns the leftmost node in a binary tree, either recursively or iteratively using tail
703
+ * recursion optimization.
704
+ * @param {N | null} [node] - The `node` parameter is an optional parameter of type `N
705
+ * | null`. It represents the starting node from which to find the leftmost node in a binary tree. If no node is
706
+ * provided, the function will use the root node of the binary tree.
707
+ * @returns The `getLeftMost` function returns the leftmost node in a binary tree.
708
+ */
709
+ getLeftMost(node?: N | null): N | null {
710
+ node = node ?? this.root;
711
+ if (!node) return node;
712
+
713
+ if (this._loopType === LoopType.recursive) {
714
+
715
+ const _traverse = (cur: N): N => {
716
+ if (!cur.left) return cur;
717
+ return _traverse(cur.left);
718
+ }
719
+
720
+ return _traverse(node);
721
+ } else {
722
+ // Indirect implementation of iteration using tail recursion optimization
723
+ const _traverse = trampoline((cur: N) => {
724
+ if (!cur.left) return cur;
725
+ return _traverse.cont(cur.left);
726
+ });
727
+
728
+ return _traverse(node);
729
+ }
730
+ }
731
+
732
+ getRightMost(): N | null;
733
+
734
+ getRightMost(node: N): N;
735
+
736
+ /**
737
+ * The `getRightMost` function returns the rightmost node in a binary tree, either recursively or iteratively using
738
+ * tail recursion optimization.
739
+ * @param {N | null} [node] - The `node` parameter is an optional parameter of type `N
740
+ * | null`. It represents the starting node from which to find the rightmost node in a binary tree. If no node is
741
+ * provided, the function will use the root node of the binary tree.
742
+ * @returns The `getRightMost` function returns the rightmost node in a binary tree.
743
+ */
744
+ getRightMost(node?: N | null): N | null {
745
+ node = node ?? this.root;
746
+ if (!node) return node;
747
+
748
+ if (this._loopType === LoopType.recursive) {
749
+ const _traverse = (cur: N): N => {
750
+ if (!cur.right) return cur;
751
+ return _traverse(cur.right);
752
+ }
753
+
754
+ return _traverse(node);
755
+ } else {
756
+ // Indirect implementation of iteration using tail recursion optimization
757
+ const _traverse = trampoline((cur: N) => {
758
+ if (!cur.right) return cur;
759
+ return _traverse.cont(cur.right);
760
+ });
761
+
762
+ return _traverse(node);
763
+ }
764
+ }
765
+
766
+ /**
767
+ * The `isBST` function checks if a binary tree is a binary search tree.
768
+ * @param {N | null} [node] - The `node` parameter is an optional parameter of type `N
769
+ * | null`. It represents the root node of the binary search tree (BST) that we want to check for validity. If no node
770
+ * is provided, the function will default to using the root node of the BST instance that
771
+ * @returns The `isBST` function returns a boolean value. It returns `true` if the binary tree is a valid binary search
772
+ * tree, and `false` otherwise.
773
+ */
774
+ isBST(node?: N | null): boolean {
775
+ node = node ?? this.root;
776
+ if (!node) return true;
777
+
778
+ if (this._loopType === LoopType.recursive) {
779
+ const dfs = (cur: N | null | undefined, min: BinaryTreeNodeId, max: BinaryTreeNodeId): boolean => {
780
+ if (!cur) return true;
781
+ if (cur.id <= min || cur.id >= max) return false;
782
+ return dfs(cur.left, min, cur.id) && dfs(cur.right, cur.id, max);
783
+ }
784
+
785
+ return dfs(node, Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
786
+ } else {
787
+ const stack = [];
788
+ let prev = Number.MIN_SAFE_INTEGER, curr: N | null | undefined = node;
789
+ while (curr || stack.length > 0) {
790
+ while (curr) {
791
+ stack.push(curr);
792
+ curr = curr.left;
793
+ }
794
+ curr = stack.pop()!;
795
+ if (!(curr) || prev >= curr.id) return false;
796
+ prev = curr.id;
797
+ curr = curr.right;
798
+ }
799
+ return true;
800
+ }
801
+ }
802
+
803
+ /**
804
+ * The function calculates the size and count of a subtree in a binary tree using either recursive or iterative
805
+ * traversal.
806
+ * @param {N | null | undefined} subTreeRoot - The `subTreeRoot` parameter is the root node of a binary
807
+ * tree.
808
+ * @returns The function `getSubTreeSizeAndCount` returns an array `[number, number]`. The first element of the array
809
+ * represents the size of the subtree, and the second element represents the count of the nodes in the subtree.
810
+ */
811
+ getSubTreeSizeAndCount(subTreeRoot: N | null | undefined) {
812
+ const res: [number, number] = [0, 0];
813
+ if (!subTreeRoot) return res;
814
+
815
+ if (this._loopType === LoopType.recursive) {
816
+ const _traverse = (cur: N) => {
817
+ res[0]++;
818
+ res[1] += cur.count;
819
+ cur.left && _traverse(cur.left);
820
+ cur.right && _traverse(cur.right);
821
+ }
822
+
823
+ _traverse(subTreeRoot);
824
+ return res;
825
+ } else {
826
+ const stack: N[] = [subTreeRoot];
827
+
828
+ while (stack.length > 0) {
829
+ const cur = stack.pop()!;
830
+ res[0]++;
831
+ res[1] += cur.count;
832
+ cur.right && stack.push(cur.right);
833
+ cur.left && stack.push(cur.left);
834
+ }
835
+
836
+ return res;
837
+ }
838
+ }
839
+
840
+ // --- start additional methods ---
841
+
842
+ /**
843
+ * The function `subTreeSum` calculates the sum of a specified property in a binary tree, either recursively or
844
+ * iteratively.
845
+ * @param subTreeRoot - The subTreeRoot parameter is the root node of the subtree for which you want to calculate the
846
+ * sum.
847
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
848
+ * specifies the property of the `BinaryTreeNode` object to use for calculating the sum. If `propertyName` is not
849
+ * provided, it defaults to `'val'`.
850
+ * @returns a number, which is the sum of the values of the nodes in the subtree rooted at `subTreeRoot`.
851
+ */
852
+ subTreeSum(subTreeRoot: N, propertyName ?: BinaryTreeNodePropertyName): number {
853
+ propertyName = propertyName ?? 'val';
854
+ if (!subTreeRoot) return 0;
855
+
856
+ let sum = 0;
857
+
858
+ const _sumByProperty = (cur: N) => {
859
+ let needSum: number;
860
+ switch (propertyName) {
861
+ case 'id':
862
+ needSum = cur.id;
863
+ break;
864
+ case 'count':
865
+ needSum = cur.count;
866
+ break;
867
+ case 'val':
868
+ needSum = typeof cur.val === 'number' ? cur.val : 0;
869
+ break;
870
+ default:
871
+ needSum = cur.id;
872
+ break;
873
+ }
874
+ return needSum;
875
+ }
876
+
877
+ if (this._loopType === LoopType.recursive) {
878
+ const _traverse = (cur: N): void => {
879
+ sum += _sumByProperty(cur);
880
+ cur.left && _traverse(cur.left);
881
+ cur.right && _traverse(cur.right);
882
+ }
883
+
884
+ _traverse(subTreeRoot);
885
+ } else {
886
+ const stack: N[] = [subTreeRoot];
887
+
888
+ while (stack.length > 0) {
889
+ const cur = stack.pop()!;
890
+ sum += _sumByProperty(cur);
891
+ cur.right && stack.push(cur.right);
892
+ cur.left && stack.push(cur.left);
893
+ }
894
+ }
895
+
896
+ return sum;
897
+ }
898
+
899
+ /**
900
+ * The function `subTreeAdd` adds a specified delta value to a property of each node in a binary tree.
901
+ * @param subTreeRoot - The `subTreeRoot` parameter is the root node of the subtree where the values will be modified.
902
+ * @param {number} delta - The `delta` parameter is a number that represents the amount by which the property value of
903
+ * each node in the subtree should be increased or decreased.
904
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
905
+ * specifies the property of the `BinaryTreeNode` that should be modified. It defaults to `'id'` if not provided.
906
+ * @returns a boolean value, which is `true`.
907
+ */
908
+ subTreeAdd(subTreeRoot: N, delta: number, propertyName ?: BinaryTreeNodePropertyName): boolean {
909
+ propertyName = propertyName ?? 'id';
910
+ if (!subTreeRoot) return false;
911
+
912
+ const _addByProperty = (cur: N) => {
913
+ switch (propertyName) {
914
+ case 'id':
915
+ cur.id += delta;
916
+ break;
917
+ case 'count':
918
+ cur.count += delta;
919
+ this._setCount(this.count + delta);
920
+ break;
921
+ default:
922
+ cur.id += delta;
923
+ break;
924
+ }
925
+ }
926
+
927
+ if (this._loopType === LoopType.recursive) {
928
+ const _traverse = (cur: N) => {
929
+ _addByProperty(cur);
930
+ cur.left && _traverse(cur.left);
931
+ cur.right && _traverse(cur.right);
932
+ };
933
+
934
+ _traverse(subTreeRoot);
935
+ } else {
936
+ const stack: N[] = [subTreeRoot];
937
+
938
+ while (stack.length > 0) {
939
+ const cur = stack.pop()!;
940
+
941
+ _addByProperty(cur);
942
+ cur.right && stack.push(cur.right);
943
+ cur.left && stack.push(cur.left);
944
+ }
945
+ }
946
+ return true;
947
+ }
948
+
949
+ BFS(): BinaryTreeNodeId[];
950
+
951
+ BFS(nodeOrPropertyName: 'id'): BinaryTreeNodeId[];
952
+
953
+ BFS(nodeOrPropertyName: 'val'): N[];
954
+
955
+ BFS(nodeOrPropertyName: 'node'): N[];
956
+
957
+ BFS(nodeOrPropertyName: 'count'): number[];
958
+
959
+ /**
960
+ * The BFS function performs a breadth-first search on a binary tree and returns the results based on a specified node
961
+ * or property name.
962
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
963
+ * represents either a node or a property name. If a node is provided, the breadth-first search algorithm will be
964
+ * performed starting from that node. If a property name is provided, the breadth-first search algorithm will be
965
+ * performed starting from the root node
966
+ * @returns an object of type `ResultsByProperty<N>`.
967
+ */
968
+ BFS(nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<N> {
969
+ nodeOrPropertyName = nodeOrPropertyName ?? 'id';
970
+ this._resetResults();
971
+ const queue: Array<N | null | undefined> = [this.root];
972
+
973
+ while (queue.length !== 0) {
974
+ const cur = queue.shift();
975
+ if (cur) {
976
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
977
+ if (cur?.left !== null) queue.push(cur.left);
978
+ if (cur?.right !== null) queue.push(cur.right);
979
+ }
980
+ }
981
+
982
+ return this._getResultByPropertyName(nodeOrPropertyName);
983
+ }
984
+
985
+ DFS(): BinaryTreeNodeId[];
986
+
987
+ DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
988
+
989
+ DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): N[];
990
+
991
+ DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): N[];
992
+
993
+ DFS(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
994
+
995
+ /**
996
+ * The DFS function performs a depth-first search traversal on a binary tree and returns the results based on the
997
+ * specified pattern and node or property name.
998
+ * @param {'in' | 'pre' | 'post'} [pattern] - The "pattern" parameter is used to specify the order in which the nodes
999
+ * of a binary tree are traversed during the Depth-First Search (DFS) algorithm. It can take one of three values: 'in',
1000
+ * 'pre', or 'post'.
1001
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is a string that represents
1002
+ * either the name of a property in the `BinaryTreeNode` object or the value of the `id` property in the
1003
+ * `BinaryTreeNode` object. This parameter is used to accumulate the results based on the specified property name. If
1004
+ * no value
1005
+ * @returns an object of type `ResultsByProperty<N>`.
1006
+ */
1007
+ DFS(pattern ?: 'in' | 'pre' | 'post', nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<N> {
1008
+ pattern = pattern ?? 'in';
1009
+ nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1010
+ this._resetResults();
1011
+ const _traverse = (node: N) => {
1012
+ switch (pattern) {
1013
+ case 'in':
1014
+ if (node.left) _traverse(node.left);
1015
+ this._accumulatedByPropertyName(node, nodeOrPropertyName);
1016
+ if (node.right) _traverse(node.right);
1017
+ break;
1018
+ case 'pre':
1019
+ this._accumulatedByPropertyName(node, nodeOrPropertyName);
1020
+ if (node.left) _traverse(node.left);
1021
+ if (node.right) _traverse(node.right);
1022
+ break;
1023
+ case 'post':
1024
+ if (node.left) _traverse(node.left);
1025
+ if (node.right) _traverse(node.right);
1026
+ this._accumulatedByPropertyName(node, nodeOrPropertyName);
1027
+ break;
1028
+ }
1029
+ };
1030
+
1031
+ this.root && _traverse(this.root);
1032
+ return this._getResultByPropertyName(nodeOrPropertyName);
1033
+ }
1034
+
1035
+ DFSIterative(): BinaryTreeNodeId[];
1036
+
1037
+ DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1038
+
1039
+ DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): N[];
1040
+
1041
+ DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): N[];
1042
+
1043
+ DFSIterative(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
1044
+
1045
+ /**
1046
+ * Time complexity is O(n)
1047
+ * Space complexity of Iterative DFS equals to recursive DFS which is O(n) because of the stack
1048
+ * @param pattern
1049
+ * @param nodeOrPropertyName
1050
+ * @constructor
1051
+ */
1052
+ DFSIterative(pattern ?: 'in' | 'pre' | 'post', nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<N> {
1053
+ pattern = pattern || 'in';
1054
+ nodeOrPropertyName = nodeOrPropertyName || 'id';
1055
+ this._resetResults();
1056
+ if (!this.root) return this._getResultByPropertyName(nodeOrPropertyName);
1057
+ // 0: visit, 1: print
1058
+ const stack: { opt: 0 | 1, node: N | null | undefined }[] = [{opt: 0, node: this.root}];
1059
+
1060
+ while (stack.length > 0) {
1061
+ const cur = stack.pop();
1062
+ if (!cur || !cur.node) continue;
1063
+ if (cur.opt === 1) {
1064
+ this._accumulatedByPropertyName(cur.node, nodeOrPropertyName);
1065
+ } else {
1066
+ switch (pattern) {
1067
+ case 'in':
1068
+ stack.push({opt: 0, node: cur.node.right});
1069
+ stack.push({opt: 1, node: cur.node});
1070
+ stack.push({opt: 0, node: cur.node.left});
1071
+ break;
1072
+ case 'pre':
1073
+ stack.push({opt: 0, node: cur.node.right});
1074
+ stack.push({opt: 0, node: cur.node.left});
1075
+ stack.push({opt: 1, node: cur.node});
1076
+ break;
1077
+ case 'post':
1078
+ stack.push({opt: 1, node: cur.node});
1079
+ stack.push({opt: 0, node: cur.node.right});
1080
+ stack.push({opt: 0, node: cur.node.left});
1081
+ break;
1082
+ default:
1083
+ stack.push({opt: 0, node: cur.node.right});
1084
+ stack.push({opt: 1, node: cur.node});
1085
+ stack.push({opt: 0, node: cur.node.left});
1086
+ break;
1087
+ }
1088
+ }
1089
+ }
1090
+
1091
+ return this._getResultByPropertyName(nodeOrPropertyName);
1092
+ }
1093
+
1094
+ levelIterative(node: N | null): BinaryTreeNodeId[];
1095
+
1096
+ levelIterative(node: N | null, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1097
+
1098
+ levelIterative(node: N | null, nodeOrPropertyName?: 'val'): N[];
1099
+
1100
+ levelIterative(node: N | null, nodeOrPropertyName?: 'node'): N[];
1101
+
1102
+ levelIterative(node: N | null, nodeOrPropertyName?: 'count'): number[];
1103
+
1104
+ /**
1105
+ * The `levelIterative` function performs a level-order traversal on a binary tree and returns the values of the nodes
1106
+ * in an array, based on a specified property name.
1107
+ * @param {N | null} node - The `node` parameter is a BinaryTreeNode object representing the starting
1108
+ * node for the level order traversal. It can be null if no specific node is provided, in which case the root node of
1109
+ * the tree is used as the starting node.
1110
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that
1111
+ * can be either a `BinaryTreeNode` property name or the string `'id'`. If a property name is provided, the function
1112
+ * will accumulate results based on that property. If no property name is provided, the function will default to
1113
+ * accumulating results
1114
+ * @returns The function `levelIterative` returns an object of type `ResultsByProperty<N>`.
1115
+ */
1116
+ levelIterative(node: N | null, nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<N> {
1117
+ nodeOrPropertyName = nodeOrPropertyName || 'id';
1118
+ node = node || this.root;
1119
+ if (!node) return [];
1120
+
1121
+ this._resetResults();
1122
+ const queue: N[] = [node];
1123
+
1124
+ while (queue.length > 0) {
1125
+ const cur = queue.shift();
1126
+ if (cur) {
1127
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1128
+ if (cur.left) {
1129
+ queue.push(cur.left);
1130
+ }
1131
+ if (cur.right) {
1132
+ queue.push(cur.right);
1133
+ }
1134
+ }
1135
+ }
1136
+
1137
+ return this._getResultByPropertyName(nodeOrPropertyName);
1138
+ }
1139
+
1140
+ listLevels(node: N | null): BinaryTreeNodeId[][];
1141
+
1142
+ listLevels(node: N | null, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[][];
1143
+
1144
+ listLevels(node: N | null, nodeOrPropertyName?: 'val'): N[][];
1145
+
1146
+ listLevels(node: N | null, nodeOrPropertyName?: 'node'): N[][];
1147
+
1148
+ listLevels(node: N | null, nodeOrPropertyName?: 'count'): number[][];
1149
+
1150
+ /**
1151
+ * The `listLevels` function collects nodes from a binary tree by a specified property and organizes them into levels.
1152
+ * @param {N | null} node - The `node` parameter is a BinaryTreeNode object or null. It represents the
1153
+ * root node of a binary tree. If it is null, the function will use the root node of the current binary tree instance.
1154
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is an optional parameter that
1155
+ * specifies the property of the `BinaryTreeNode` object to collect at each level. It can be one of the following
1156
+ * values:
1157
+ * @returns The function `listLevels` returns a 2D array of `ResultByProperty<N>` objects.
1158
+ */
1159
+ listLevels(node: N | null, nodeOrPropertyName?: NodeOrPropertyName): ResultByProperty<N>[][] {
1160
+ nodeOrPropertyName = nodeOrPropertyName || 'id';
1161
+ node = node || this.root;
1162
+ if (!node) return [];
1163
+
1164
+ const levelsNodes: ResultByProperty<N>[][] = [];
1165
+
1166
+ const collectByProperty = (node: N, level: number) => {
1167
+ switch (nodeOrPropertyName) {
1168
+ case 'id':
1169
+ levelsNodes[level].push(node.id);
1170
+ break;
1171
+ case 'val':
1172
+ levelsNodes[level].push(node.val);
1173
+ break;
1174
+ case 'node':
1175
+ levelsNodes[level].push(node);
1176
+ break;
1177
+ case 'count':
1178
+ levelsNodes[level].push(node.count);
1179
+ break;
1180
+ default:
1181
+ levelsNodes[level].push(node.id);
1182
+ break;
1183
+ }
1184
+ }
1185
+
1186
+ if (this._loopType === LoopType.recursive) {
1187
+ const _recursive = (node: N, level: number) => {
1188
+ if (!levelsNodes[level]) levelsNodes[level] = [];
1189
+ collectByProperty(node, level);
1190
+ if (node.left) _recursive(node.left, level + 1);
1191
+ if (node.right) _recursive(node.right, level + 1);
1192
+ };
1193
+
1194
+ _recursive(node, 0);
1195
+ } else {
1196
+ const stack: [N, number][] = [[node, 0]];
1197
+
1198
+ while (stack.length > 0) {
1199
+ const head = stack.pop()!;
1200
+ const [node, level] = head;
1201
+
1202
+ if (!levelsNodes[level]) levelsNodes[level] = [];
1203
+ collectByProperty(node, level);
1204
+ if (node.right) stack.push([node.right, level + 1]);
1205
+ if (node.left) stack.push([node.left, level + 1]);
1206
+ }
1207
+ }
1208
+
1209
+ return levelsNodes;
1210
+ }
1211
+
1212
+ /**
1213
+ * The function returns the predecessor of a given node in a binary tree.
1214
+ * @param node - The parameter `node` is a BinaryTreeNode object, representing a node in a binary tree.
1215
+ * @returns the predecessor of the given node in a binary tree.
1216
+ */
1217
+ getPredecessor(node: N): N {
1218
+ if (node.left) {
1219
+ let predecessor: N | null | undefined = node.left;
1220
+ while (!(predecessor) || predecessor.right && predecessor.right !== node) {
1221
+ if (predecessor) {
1222
+ predecessor = predecessor.right;
1223
+ }
1224
+ }
1225
+ return predecessor;
1226
+ } else {
1227
+ return node;
1228
+ }
1229
+ }
1230
+
1231
+ morris(): BinaryTreeNodeId[];
1232
+
1233
+ morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'id'): BinaryTreeNodeId[];
1234
+
1235
+ morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'val'): N[];
1236
+
1237
+ morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'node'): N[];
1238
+
1239
+ morris(pattern?: DFSOrderPattern, nodeOrPropertyName?: 'count'): number[];
1240
+
1241
+ /**
1242
+ * The `morris` function performs an in-order, pre-order, or post-order traversal on a binary tree using the Morris
1243
+ * traversal algorithm and returns the results based on the specified property name.
1244
+ * The time complexity of Morris traversal is O(n), it's may slower than others
1245
+ * The space complexity Morris traversal is O(1) because no using stack
1246
+ * @param {'in' | 'pre' | 'post'} [pattern] - The `pattern` parameter is an optional parameter that determines the
1247
+ * traversal pattern of the binary tree. It can have one of three values:
1248
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The `nodeOrPropertyName` parameter is used to specify the
1249
+ * property of the nodes that you want to retrieve in the results. It can be either the node itself or the name of the
1250
+ * property. If not provided, it defaults to `'id'`.
1251
+ * @returns The function `morris` returns an object of type `ResultsByProperty<N>`.
1252
+ */
1253
+ morris(pattern?: 'in' | 'pre' | 'post', nodeOrPropertyName?: NodeOrPropertyName): ResultsByProperty<N> {
1254
+ if (this.root === null) return [];
1255
+
1256
+ pattern = pattern || 'in';
1257
+ nodeOrPropertyName = nodeOrPropertyName || 'id';
1258
+
1259
+ this._resetResults();
1260
+
1261
+ let cur: N | null | undefined = this.root;
1262
+ const _reverseEdge = (node: N | null | undefined) => {
1263
+ let pre: N | null | undefined = null;
1264
+ let next: N | null | undefined = null;
1265
+ while (node) {
1266
+ next = node.right;
1267
+ node.right = pre;
1268
+ pre = node;
1269
+ node = next;
1270
+ }
1271
+ return pre;
1272
+ };
1273
+ const _printEdge = (node: N | null) => {
1274
+ const tail: N | null | undefined = _reverseEdge(node);
1275
+ let cur: N | null | undefined = tail;
1276
+ while (cur) {
1277
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1278
+ cur = cur.right;
1279
+ }
1280
+ _reverseEdge(tail);
1281
+ };
1282
+ switch (pattern) {
1283
+ case 'in':
1284
+ while (cur) {
1285
+ if (cur.left) {
1286
+ const predecessor = this.getPredecessor(cur);
1287
+ if (!predecessor.right) {
1288
+ predecessor.right = cur;
1289
+ cur = cur.left;
1290
+ continue;
1291
+ } else {
1292
+ predecessor.right = null;
1293
+ }
1294
+ }
1295
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1296
+ cur = cur.right;
1297
+ }
1298
+ break;
1299
+ case 'pre':
1300
+ while (cur) {
1301
+ if (cur.left) {
1302
+ const predecessor = this.getPredecessor(cur);
1303
+ if (!predecessor.right) {
1304
+ predecessor.right = cur;
1305
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1306
+ cur = cur.left;
1307
+ continue;
1308
+ } else {
1309
+ predecessor.right = null;
1310
+ }
1311
+ } else {
1312
+ this._accumulatedByPropertyName(cur, nodeOrPropertyName);
1313
+ }
1314
+ cur = cur.right;
1315
+ }
1316
+ break;
1317
+ case 'post':
1318
+ while (cur) {
1319
+ if (cur.left) {
1320
+ const predecessor = this.getPredecessor(cur);
1321
+ if (predecessor.right === null) {
1322
+ predecessor.right = cur;
1323
+ cur = cur.left;
1324
+ continue;
1325
+ } else {
1326
+ predecessor.right = null;
1327
+ _printEdge(cur.left);
1328
+ }
1329
+ }
1330
+ cur = cur.right;
1331
+ }
1332
+ _printEdge(this.root);
1333
+ break;
1334
+ }
1335
+
1336
+ return this._getResultByPropertyName(nodeOrPropertyName);
1337
+ }
1338
+
1339
+ protected _setLoopType(value: LoopType) {
1340
+ this._loopType = value;
1341
+ }
1342
+
1343
+ protected _setVisitedId(value: BinaryTreeNodeId[]) {
1344
+ this._visitedId = value;
1345
+ }
1346
+
1347
+ protected _setVisitedVal(value: Array<N>) {
1348
+ this._visitedVal = value;
1349
+ }
1350
+
1351
+ protected _setVisitedNode(value: N[]) {
1352
+ this._visitedNode = value;
1353
+ }
1354
+
1355
+ protected setVisitedCount(value: number[]) {
1356
+ this._visitedCount = value;
1357
+ }
1358
+
1359
+ protected _setVisitedLeftSum(value: number[]) {
1360
+ this._visitedLeftSum = value;
1361
+ }
1362
+
1363
+ protected _setAutoIncrementId(value: boolean) {
1364
+ this._autoIncrementId = value;
1365
+ }
1366
+
1367
+ protected _setMaxId(value: number) {
1368
+ this._maxId = value;
1369
+ }
1370
+
1371
+ protected _setIsDuplicatedVal(value: boolean) {
1372
+ this._isDuplicatedVal = value;
1373
+ }
1374
+
1375
+ protected _setRoot(v: N | null) {
1376
+ if (v) {
1377
+ v.parent = null;
1378
+ v.familyPosition = FamilyPosition.root;
1379
+ }
1380
+ this._root = v;
1381
+ }
1382
+
1383
+ protected _setSize(v: number) {
1384
+ this._size = v;
1385
+ }
1386
+
1387
+ protected _setCount(v: number) {
1388
+ this._count = v;
1389
+ }
1390
+
1391
+ /**
1392
+ * The function resets the values of several arrays used for tracking visited nodes and their properties.
1393
+ */
1394
+ protected _resetResults() {
1395
+ this._visitedId = [];
1396
+ this._visitedVal = [];
1397
+ this._visitedNode = [];
1398
+ this._visitedCount = [];
1399
+ this._visitedLeftSum = [];
1400
+ }
1401
+
1402
+ /**
1403
+ * The function checks if a given property of a binary tree node matches a specified value, and if so, adds the node to
1404
+ * a result array.
1405
+ * @param cur - The current binary tree node that is being checked.
1406
+ * @param {(N | null | undefined)[]} result - An array that stores the matching nodes found during the
1407
+ * traversal.
1408
+ * @param {BinaryTreeNodeId | N} nodeProperty - The `nodeProperty` parameter is the value that we are searching for in
1409
+ * the binary tree nodes. It can be either the `id`, `count`, or `val` property of the node.
1410
+ * @param {BinaryTreeNodePropertyName} [propertyName] - The `propertyName` parameter is an optional parameter that
1411
+ * specifies the property of the `BinaryTreeNode` object that you want to compare with the `nodeProperty` value. It can
1412
+ * be one of the following values: 'id', 'count', or 'val'. If no `propertyName` is provided,
1413
+ * @param {boolean} [onlyOne] - The `onlyOne` parameter is an optional boolean parameter that determines whether to
1414
+ * stop after finding the first matching node or continue searching for all matching nodes. If `onlyOne` is set to
1415
+ * `true`, the function will stop after finding the first matching node and return `true`. If `onlyOne
1416
+ * @returns a boolean value indicating whether or not a node was pushed into the result array.
1417
+ */
1418
+ protected _pushByPropertyNameStopOrNot(cur: N, result: (N | null | undefined)[], nodeProperty: BinaryTreeNodeId | N, propertyName ?: BinaryTreeNodePropertyName, onlyOne ?: boolean) {
1419
+ switch (propertyName) {
1420
+ case 'id':
1421
+ if (cur.id === nodeProperty) {
1422
+ result.push(cur);
1423
+ return !!onlyOne;
1424
+ }
1425
+ break;
1426
+ case 'count':
1427
+ if (cur.count === nodeProperty) {
1428
+ result.push(cur);
1429
+ return !!onlyOne;
1430
+ }
1431
+ break;
1432
+ case 'val':
1433
+ if (cur.val === nodeProperty) {
1434
+ result.push(cur);
1435
+ return !!onlyOne;
1436
+ }
1437
+ break;
1438
+ default:
1439
+ if (cur.id === nodeProperty) {
1440
+ result.push(cur);
1441
+ return !!onlyOne;
1442
+ }
1443
+ break;
1444
+ }
1445
+ }
1446
+
1447
+ /**
1448
+ * The function `_accumulatedByPropertyName` pushes a property value of a binary tree node into an array based on the
1449
+ * provided property name or a default property name.
1450
+ * @param node - The `node` parameter is of type `N`, which represents a node in a binary tree.
1451
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
1452
+ * can be either a string representing a property name or a reference to a node object. If it is a string, it specifies
1453
+ * the property name of the node that should be accumulated. If it is a node object, it specifies the node itself
1454
+ */
1455
+ protected _accumulatedByPropertyName(node: N, nodeOrPropertyName ?: NodeOrPropertyName) {
1456
+ nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1457
+
1458
+ switch (nodeOrPropertyName) {
1459
+ case 'id':
1460
+ this._visitedId.push(node.id);
1461
+ break;
1462
+ case 'val':
1463
+ this._visitedVal.push(node.val);
1464
+ break;
1465
+ case 'node':
1466
+ this._visitedNode.push(node);
1467
+ break;
1468
+ case 'count':
1469
+ this._visitedCount.push(node.count);
1470
+ break;
1471
+ default:
1472
+ this._visitedId.push(node.id);
1473
+ break;
1474
+ }
1475
+ }
1476
+
1477
+ /**
1478
+ * The function `_getResultByPropertyName` returns different results based on the provided property name or defaulting
1479
+ * to 'id'.
1480
+ * @param {NodeOrPropertyName} [nodeOrPropertyName] - The parameter `nodeOrPropertyName` is an optional parameter that
1481
+ * can accept a value of type `NodeOrPropertyName`.
1482
+ * @returns The method returns an object of type `ResultsByProperty<T>`.
1483
+ */
1484
+ protected _getResultByPropertyName(nodeOrPropertyName ?: NodeOrPropertyName): ResultsByProperty<N> {
1485
+ nodeOrPropertyName = nodeOrPropertyName ?? 'id';
1486
+
1487
+ switch (nodeOrPropertyName) {
1488
+ case 'id':
1489
+ return this._visitedId;
1490
+ case 'val':
1491
+ return this._visitedVal;
1492
+ case 'node':
1493
+ return this._visitedNode;
1494
+ case 'count':
1495
+ return this._visitedCount;
1496
+ default:
1497
+ return this._visitedId;
1498
+ }
1499
+ }
1500
+
1501
+ // --- end additional methods ---
1502
+ }