JS-树:深度优先搜索与广度优先搜索



前言

最近总结一下树的算法,研究树相关的知识。


一、深度优先搜索

1、从根出发,尽可能深的搜索树的节点
2、如下输入是:a b d e c f g

 // 树的深度优先搜索
  const tree = {
    
    
    val: 'a',
    children: [
      {
    
    
        val: 'b',
        children: [
          {
    
    
            val: 'd',
            children: [],
          },
          {
    
    
            val: 'e',
            children: [],
          },
        ],
      },
      {
    
    
        val: 'c',
        children: [
          {
    
    
            val: 'f',
            children: [],
          },
          {
    
    
            val: 'g',
            children: [],
          },
        ],
      },
    ],
  }
	
  // 深度优先搜索
  fun1(tree)

function fun1(root: any) {
    
    
  console.log(root.val)
  root.children.forEach(fun1)
}

二、广度优先搜索

1、从根出发,优先搜索离根节点最近的节点
2、如下输入是:a b c d e f g

function fun2(root: any) {
    
    
  const arr = [root]
  while (arr.length > 0) {
    
    
    const o = arr.shift()
    console.log(o.val)
    o.children.forEach((item) => {
    
    
      arr.push(item)
    })
  }
}

总结

这就是树的深度优先搜索和树的广度优先搜索,希望能帮助到你!

猜你喜欢

转载自blog.csdn.net/smileKH/article/details/133702817