深度优先遍历实现方式1
let tree = {
id: '1',
title: '节点1',
children: [
{
id: '1-1',
title: '节点1-1'
},
{
id: '1-2',
title: '节点1-2',
children: [{
id: '2',
title: '节点2',
children: [
{
id: '2-1',
title: '节点2-1'
}
]
}]
}
]
}
let deepTraversal1 = (node, nodeList = []) => {
if (node !== null) {
nodeList.push(node.id)
if(node.children && node.children.length>0){
let children = node.children
for (let i = 0; i < children.length; i++) {
deepTraversal1(children[i], nodeList)
}
}
}
return nodeList
}
console.log(deepTraversal1(tree))
深度优先遍历实现方式2
let tree = {
id: '1',
title: '节点1',
children: [
{
id: '1-1',
title: '节点1-1'
},
{
id: '1-2',
title: '节点1-2',
children: [{
id: '2',
title: '节点2',
children: [
{
id: '2-1',
title: '节点2-1'
}
]
}]
}
]
}
let deepTraversal2 = (node) => {
let nodes = []
if (node !== null) {
nodes.push(node.id)
if(node.children && node.children.length>0){
let children = node.children
for (let i = 0; i < children.length; i++) {
nodes = nodes.concat(deepTraversal2(children[i]))
}
}
}
return nodes
}
console.log(deepTraversal2(tree))
深度优先遍历实现方式3 ,非递归的方式
let tree = {
id: '1',
title: '节点1',
children: [
{
id: '1-1',
title: '节点1-1'
},
{
id: '1-2',
title: '节点1-2',
children: [{
id: '2',
title: '节点2',
children: [
{
id: '2-1',
title: '节点2-1'
}
]
}]
}
]
}
let widthTraversal3 = (node) => {
let nodes = []
let stack = []
if(node){
stack.push(node)
while(stack.length){
let item = stack.shift()
let children = item.children
nodes.push(item.id)
if(children){
for(var i=0;i<children.length;i++){
stack.push(children[i])
}
}
}
}
return nodes
}
console.log(widthTraversal3(tree))
广度优先搜索
let tree = [
{
id: '1',
title: '节点1',
children: [
{
id: '1-1',
title: '节点1-1'
},
{
id: '1-2',
title: '节点1-2'
}
]
},
{
id: '2',
title: '节点2',
children: [
{
id: '2-1',
title: '节点2-1'
}
]
}
]
function treeForeach(tree,func){
let node,list = [...tree]
while(node = list.shift()){
func(node)
node.children && list.push(...node.children)
}
}
treeForeach(tree,node => console.log(node.title))
console.log(tree);
几种使用方法主要是树结构的数据处理时候用。
|