Add TypeScript code and docs to AVL tree and the coding style for Typescript and JavaScript (#342)

* Add TypeScript code and docs to AVL tree and update JavaScript style

* Update the coding style for Typescript and JavaScript
This commit is contained in:
Justin Tse
2023-02-07 01:21:58 +08:00
committed by GitHub
parent 7f4243ab77
commit b14568151c
9 changed files with 453 additions and 49 deletions
+18 -1
View File
@@ -31,4 +31,21 @@ function arrToLinkedList(arr: number[]): ListNode | null {
return dum.next;
}
export { ListNode, arrToLinkedList };
/**
* Get a list node with specific value from a linked list
* @param head
* @param val
* @return
*/
function getListNode(head: ListNode | null, val: number): ListNode | null {
while (head !== null && head.val !== val) {
head = head.next;
}
return head;
}
export {
ListNode,
arrToLinkedList,
getListNode
};
+10 -9
View File
@@ -8,14 +8,15 @@
* Definition for a binary tree node.
*/
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val; // 结点值
this.left = left === undefined ? null : left; // 左子结点指针
this.right = right === undefined ? null : right; // 右子结点指针
val: number; // 结点值
height: number; // 结点高度
left: TreeNode | null; // 左子结点指针
right: TreeNode | null; // 右子结点指针
constructor(val?: number, height?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = val === undefined ? 0 : val;
this.height = height === undefined ? 0 : height;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
}
@@ -33,7 +34,7 @@ function arrToTree(arr: (number | null)[]): TreeNode | null {
const queue = [root];
let i = 0;
while (queue.length) {
let node = queue.shift() as TreeNode;
const node = queue.shift() as TreeNode;
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.left = new TreeNode(arr[i] as number);