[路飞]_数组层序构建二叉树

656 阅读1分钟

为什么要构建二叉树

在刷leetcode的时候经常遇到二叉树问题;但是输入的二叉树leetcode给的是个数组;写个用例想调试一下只能在leetcode中才能正常运行,因为本地编辑器没有将数组转换为二叉树的方法,用例又要操作二叉树;于是决定研究一下给一个数组,将数组转为二叉树;

层序二叉树

输入: 比如输入数组array = [1,2,3,4,5,6,7] 输出:

       1
     /   \
    2     3
   / \   / \  
  4   5 6   7 

代码如下

function createTreeByArray(list) {
  function TreeNode(val) {
    this.val = val
    this.left = null
    this.right = null
  }
  if (list.length === 0) return null
  let tree = new TreeNode(list[0])
  let root = [tree]
  let index = 1;
  for (node of root) {
    root.push((node.left = new TreeNode(list[index])))
    index++
    if (index === list.length) return tree
    root.push((node.right = new TreeNode(list[index])))
    index++
    if (index === list.length) return tree
  }
}