Instance data:
let tree = [
{
id: '1'.children: [{id: 1-1 ' '.children: [{id: '1-1-1'}, {id: '1-1-2',},],}, {id: '2'.children: [{id: '1-2-1'}, {id: '1-2-2',},],},],}, {id: '2'.children: [{id: '2-1'.children: [{id: '2-1-1'}, {id: '2-1-2',},],}, {id: '2-2'.children: [{id: '2-2-1',},],},],}, {id: '3'.children: [{id: '3-1'.children: [{id: '3-1-1',},],}, {id: '3-2'.children: [{id: '3-2-1',},],}, {id: '3-3'.children: [{id: '3-3-1',},],},]Copy the code
Depth traversal
Depth-first-search is a type of Search algorithm that traverses the nodes of a tree along its Depth, searching branches of the tree as deep as possible. The idea is to find a node, find out its descendants; And so on.
- Recursive method
const deepTree = (data, arr = []) = > {
for (let i = 0; i < data.length; i++) {
let item = data[i]
arr.push(item.id)
if (item.children && item.children.length) {
deepTree(item.children, arr)
}
}
return arr
}
Copy the code
- The while loop
const deepTree2 = (data) = > {
let stack = []
let arr = []
stack = data
while (stack.length) {
let item = stack.shift()
let children = item.children
arr.push(item.id)
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
stack.unshift(children[i])
}
}
}
return arr
}
Copy the code
Iterate through the result
Breadth traversal
Breadth First Search starts with a node and tries to access the target node as close to it as possible. In essence, this traversal moves layer by layer, first checking the layer closest to the first node, and then gradually moving down to the layer farthest from the start node.
const widthTree = (data) = > {
let stack = []
let arr = []
stack = data
while (stack.length) {
let item = stack.shift()
let children = item.children
arr.push(item.id)
if (children) {
for (let i = 0; i < children.length; i++) {
stack.push(children[i])
}
}
}
return arr
}
Copy the code
Iterate through the result