mirror of
https://github.com/krahets/hello-algo.git
synced 2025-07-06 14:27:26 +08:00
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:
@ -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;
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user