How to create a Binary Tree by Array of data?

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]:

  1. left child index = i * 2 + 1
  2. right child index = i * 2 + 2
  3. 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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值