數(shù)據(jù)
var tree = [
{
name: "A",
children: [
{
name: "B",
children: [
{
name: "E"
},
{
name: "F"
}
]
},
{
name: "C",
children: [
{
name: "G"
},
{
name: "H"
}
]
},
{
name: "D",
children: [
{
name: "I"
},
{
name: "J"
}
]
}
]
}
]
廣度優(yōu)先遍歷
var list = []
function wideSearch(tree) {
let nodes = []
nodes = nodes.concat(tree)
var shift = nodes.shift()
list.push(shift)
if (shift.children) {
nodes = nodes.concat(shift.children)
}
if (nodes.length > 0) {
wideSearch(nodes)
}
return nodes
}
深度優(yōu)先遍歷
var list = []
function deepSearch(tree) {
for (var i = 0; i < tree.length; i++) {
list.push(tree[i].name)
if (tree[i].children) {
deepSearch(tree[i].children)
}
}
}
深度優(yōu)先不遞歸
function deepSearchStack(tree) {
var stack = []
var result = []
stack = stack.concat(tree)
while (stack.length > 0) {
var node = stack.pop()
result.push(node.name)
if (node.children) {
stack = stack.concat(node.children.reverse())
}
}
console.log(result)
}
deepSearchStack(tree)