Trees in js and priority traversal!

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:

  1. visit root stage
  2. Depth-first traversal of each element of the children of the root node
    insert image description here
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:

  1. Create a new queue and enqueue the root node
  2. Dequeue the head of the queue and access
  3. Put the children elements at the head of the team into the team respectively
  4. Repeat steps 2 and 3 until the queue is empty
    insert image description here
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

  1. DOM tree
  2. cascade selection
  3. tree control
  4. Organization Chart

Original Link: Vegetable Garden Front End

Guess you like

Origin blog.csdn.net/qq2603375880/article/details/131396642