feat(tree): Add the array representation of the binary tree(js,ts) (#681)

* fix: fixed the bug of arrToTree function

* feat(tree): Add the array representation of the binary tree(js,ts)

* refactor: Make the arrToTree method match the method in java
This commit is contained in:
William Yuan
2023-08-13 19:30:50 +08:00
committed by GitHub
parent 10c397b172
commit ec82be7dc2
4 changed files with 309 additions and 38 deletions
+5 -19
View File
@@ -30,27 +30,13 @@ class TreeNode {
* @param arr
* @return
*/
function arrToTree(arr: (number | null)[]): TreeNode | null {
if (arr.length === 0) {
function arrToTree(arr: (number | null)[], i: number = 0): TreeNode | null {
if (i < 0 || i >= arr.length || arr[i] === null) {
return null;
}
const root = new TreeNode(arr[0] as number);
const queue = [root];
let i = 0;
while (queue.length) {
const node = queue.shift() as TreeNode;
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.left = new TreeNode(arr[i] as number);
queue.push(node.left);
}
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.right = new TreeNode(arr[i] as number);
queue.push(node.right);
}
}
let root = new TreeNode(arr[i]);
root.left = arrToTree(arr, 2 * i + 1);
root.right = arrToTree(arr, 2 * i + 2);
return root;
}