[掘金笔记]回溯算法返回树结构路径集合

186 阅读1分钟
function getTreePathByValue(value, tree, options = {
  children: 'children',
  valueId: 'valueId'
}) {
  const valueId = options.valueId
  const children = options.children
  const path = []
  let result = []
  function backTrace(tree) {
      let top = path[path.length - 1]
      if (top && top === value) {
          result = path.slice(0)
      }
      if (result.length) return
      if (!tree || !tree.length) return
      for (let i = 0; i < tree.length && !result.length; i++) {
          let item = tree[i]
          path.push(item[valueId])
          backTrace(item[children])
          path.pop()
      }
  }
  backTrace(tree)
  return result
}