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

View File

@ -25,26 +25,13 @@ class TreeNode {
* @param arr
* @return
*/
function arrToTree(arr) {
if (arr.length === 0) return null;
let root = new TreeNode(arr[0]);
let queue = [root];
let i = 0;
while (queue.length) {
let node = queue.shift();
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.left = new TreeNode(arr[i]);
queue.push(node.left);
}
if (++i >= arr.length) break;
if (arr[i] !== null) {
node.right = new TreeNode(arr[i]);
queue.push(node.right);
}
function arrToTree(arr, i = 0) {
if (i < 0 || i >= arr.length || arr[i] === null) {
return null;
}
let root = new TreeNode(arr[i]);
root.left = arrToTree(arr, 2 * i + 1);
root.right = arrToTree(arr, 2 * i + 2);
return root;
}