Skip to content

Instantly share code, notes, and snippets.

@Axighi
Last active April 20, 2021 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Axighi/8fee9e425ca83a7faa95d1074c8596be to your computer and use it in GitHub Desktop.
Save Axighi/8fee9e425ca83a7faa95d1074c8596be to your computer and use it in GitHub Desktop.
Convert LeetCode Array Binary Tree To Tree Structure
// Definition for a binary tree node.
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
/**
* @param {Array<Number>} nodes
* @return {null | TreeNode}
*/
function buildBinaryTreeFromArray(nodes) {
if (nodes.length === 0) return null;
const root = new TreeNode(nodes[0]);
function recurse(node, index) {
if (!node || index === nodes.length - 1) return;
const leftIndex = 2 * index + 1;
const rightIndex = 2 * index + 2;
node.left = nodes[leftIndex] ? new TreeNode(nodes[leftIndex]) : null;
node.right = nodes[rightIndex] ? new TreeNode(nodes[rightIndex]) : null;
recurse(node.left, leftIndex);
recurse(node.right, rightIndex);
}
recurse(root, 0);
return root;
}
const t = buildBinaryTreeFromArray([1, 2, 3, null, 4]);
console.log(t);
// 1
// / \
// / \
// 2 3
// \
// \
// 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment