树的路径搜索

let tree = {
  val: '计算机学院',
  children: [{
      val: '软件工程',
      children: [{
          val: '一班',
          children: []
        },
        {
          val: '二班',
          children: []
        }
      ]
    },
    {
      val: '计算机科学与技术',
      children: [{
        val: '计算机一班',
        children: []
      }]
    }
  ]
}

function search(node, target) {
  let result = []
  let searchTarget = function(node, target, result) {
    result.push(node.val)
    if (node.val === target) {
      return result
    } else {
      for (let i = 0; i < node.children.length; i++) {
        let arr = searchTarget(node.children[i], target, result.slice())
        if (arr[arr.length - 1] === target) {
          return arr
        }
      }
      return result.slice(0, result.length - 1)
    }
  }
  return searchTarget(node, target, result)
}

console.log(search(tree, '计算机一班'))

// [ '计算机学院', '计算机科学与技术', '计算机一班' ]

你可能感兴趣的:(算法,树)