Convert LeetCode Array Binary Tree To Tree Structure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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