讨论/算法和数据结构/哪位可以作出这个算法题目?/
哪位可以作出这个算法题目?

字节一面题目:
这题目看着简单,但就是不知道怎么写出来,哪位不吝赐教,写下你的代码
WechatIMG3.png

展开讨论

递归生成n叉树,虽然难度是中等,但是n叉树很少写,写了差不多1小时,但是面试紧张难写出来。

let listToTree = function(list) {
  if (list === null || list.length === 0) {
    return []
  }

  let TreeNode = function(name) {
    this.name = name
    this.child = []
  }

  let generateTree = function(start, end) {
    let node = new TreeNode(list[start])
    node.child = listToTree(list.slice(start + 1, end + 1))

    return node
  }

  let core = function(start, end) {
    let slow = start
    let fast = start
    while (fast <= end) {
      fast++
      while (fast <= end && list[slow].slice(1) < list[fast].slice(1)) {
        fast++
      }
      result.push(generateTree(slow, fast - 1))
      slow = fast
    }
  }

  let result = []
  core(0, list.length - 1)

  return result
}
展开全部 4 讨论