Question
You might want to create a binary tree easily when you resolve algorithm questions, like me.
Thinking
Old thoughts are not good since I figure out the math basic knowledge… Here the updates:
We know that array to fill a full filled tree has functions:
for node[i]:
- left child index = i * 2 + 1
- right child index = i * 2 + 2
- parent index = Math.floor((i - 1) / 2)
- …
So main logic is to fill up the array from bottom to top, since the children are needed first.
Main logic
basic logic codes in Javascript.
function TreeNode(val = 0, left = null, right = null) {
this.val = val
this.left = left
this.right = right
}
function createBT(arr) {
for (let i = arr.length - 1; i >= 0; i--)
if (arr[i] !== null)
arr[i] = new TreeNode(arr[i], arr[i*2+1], arr[i*2+2])
return arr[0]
}
Here is one of the test cases.
const t1 = createBT([1,2,3,null,5])
console.assert(t1.val === 1)
console.assert(t1.left.val === 2)
console.assert(t1.right.val === 3)
console.assert(t1.left.left === null)
console.assert(t1.left.right.val === 5)