Open ZhengXingchi opened 4 years ago
function bfs(node) {
let quene = []
let nodeList = []
nodeList.push(node)
quene.push(node)
do {
let current = quene.shift()
nodeList.push(current)
let children = current.children
if (chiledren.length > 0) {
children.forEach(i => [
quene.push(i)
])
}
} while (quene.length > 0)
}
function bfs(node, nodeList = [], count = 0) {
if (nodeList.length === 0) {
nodeList.push(node)
} else {
let children = node.children
if (children.length > 0) {
nodeList = nodeList.concat(children)
}
}
bfs(nodeList[count], nodeList, count++)
return nodeList
}
function dfs(obj) {
let target
if (typeof obj !== 'object') {
return obj
}
if (type(obj) === '[object Array]') {
let output = []
obj.forEach(i => {
output.push(dfs(i))
})
return output
}
if (type(obj) === '[object Object]') {
let output = {}
Object.keys(obj).forEach(key => {
output[key] = dfs(obj[key])
})
return output
}
}
function type(v) {
return Object.prototype.toString.call(v)
}
function bfs(obj) {
let quene = []
let target = getEmpty(obj)
if (target !== obj) {
quene.push([obj, target])
}
while (quene.length) {
let [o, tar] = quene.shift()
for (let i in o) {
tar[i] = getEmpty(o[i])
if (tar[i] !== o[i]) {
quene.push([o[i], tar[i]])
}
}
}
return target
}
function getEmpty(o) {
if (Object.prototype.toString.call(o) === '[object Object]') {
return {}
}
else if (Object.prototype.toString.call(o) === '[object Array]') {
return []
}
else {
return o
}
}
深度优先遍历方式
深度优先stack方式