functionNode(value){this.value = value
this.children =[]}let a =newNode('a')let b =newNode('b')let c =newNode('c')let d =newNode('d')let e =newNode('e')let f =newNode('f')
a.children.push(c)
a.children.push(b)
a.children.push(f)
b.children.push(d)
b.children.push(e)functiondeepSearch(root, target){if(root ==null)returnfalseif(root.value == target)returntruelet result =falsefor(let i =0; i < root.children.length; i++){
result |=deepSearch(root.children[i], target)}return result ?true:false}
console.log(deepSearch(a,'c'))
树的广度优先搜索
functionNode(value){this.value = value
this.children =[]}let a =newNode('a')let b =newNode('b')let c =newNode('c')let d =newNode('d')let e =newNode('e')let f =newNode('f')
a.children.push(c)
a.children.push(b)
a.children.push(f)
b.children.push(d)
b.children.push(e)functionbfs(roots, target){if(roots ==null|| roots.length ==0)returnfalselet children =[]for(let i =0; i < roots.length; i++){if(roots[i].value == target){returntrue}else{
children = children.concat(roots[i].children)}}returnbfs(children, target)}
console.log(bfs([a],'n'))
图的深度优先搜索
functionNode(value){this.value = value
this.neighbor =[]}let a =newNode('a')let b =newNode('b')let c =newNode('c')let d =newNode('d')let e =newNode('e')
a.neighbor.push(b)
a.neighbor.push(c)
b.neighbor.push(a)
b.neighbor.push(c)
b.neighbor.push(d)
c.neighbor.push(a)
c.neighbor.push(b)
c.neighbor.push(d)
d.neighbor.push(b)
d.neighbor.push(c)
d.neighbor.push(e)
e.neighbor.push(d)functiondeepSearch(node, target, path){if(node ==null)returnfalseif(path.indexOf(node)>-1)returnfalseif(node.value == target)returntrue
path.push(node)let result =falsefor(let i =0; i < node.neighbor.length; i++){
result |=deepSearch(node.neighbor[i], target, path)}return result ?true:false}
console.log(deepSearch(a,'d',[]))
图的广度优先搜索
functionNode(value){this.value = value
this.neighbor =[]}let a =newNode('a')let b =newNode('b')let c =newNode('c')let d =newNode('d')let e =newNode('e')
a.neighbor.push(b)
a.neighbor.push(c)
b.neighbor.push(a)
b.neighbor.push(c)
b.neighbor.push(d)
c.neighbor.push(a)
c.neighbor.push(b)
c.neighbor.push(d)
d.neighbor.push(b)
d.neighbor.push(c)
d.neighbor.push(e)
e.neighbor.push(d)functionbfs(nodes, target, path){if(nodes ==null|| nodes.length ==0)returnfalselet nextNodes =[]for(let i =0; i < nodes.length; i++){if(path.indexOf(nodes[i])>-1)continue
path.push(nodes[i])if(nodes[i].value == target)returntrueelse nextNodes = nextNodes.concat(nodes[i].neighbor)}returnbfs(nextNodes, target, path)}
console.log(bfs([a],'c',[]))