Tree
What is a tree?
In life, everyone is no stranger to trees. Children know that trees are a kind of plant, and there are all kinds of trees no matter where they are. But what is a tree in computer science? An abstract model of hierarchical data that is ubiquitous in our front-end work. There is no such data structure as a tree in JavaScript, but a tree can be constructed from two data structures, Object and Array.
Depth and breadth first traversal
Depth-first traversal
Search the branches of the tree as deeply as possible, mainly through recursion.
Mantra:
- visit root stage
- Depth-first traversal of each element of the children of the root node
function dfs(root) {
console.log(root.value)
root.children.forEach(dfs)
}
breadth first traversal
Visit the node closest to the root node first, mainly through queues.
Mantra:
- Create a new queue and enqueue the root node
- Dequeue the head of the queue and access
- Put the children elements at the head of the team into the team respectively
- Repeat steps 2 and 3 until the queue is empty
function bfs(root) {
const q = [root]
while (q.length) {
const n = q.shift()
console.log(n)
n.children.forEach((child) => {
q.push(child)
})
}
}
common operation
- Depth-first traversal
- breadth first traversal
Application Scenario
- DOM tree
- cascade selection
- tree control
- Organization Chart
Original Link: Vegetable Garden Front End