A tree is a non-linear data structure — a collection of nodes connected by directed (or undirected) edges. Each node contains a **value **andthe connection between nodes is called edges. The top-most node is called root, a node without children is called leaf node. Nodes with same the same parent called siblings. The depth of a node is the number of edges from the root to the node and the height of a node is the number of edges from the node to the deepest leaf.

How can we visit every node in a tree? The common algorithms of traversing a tree are breadth-first search(BFS) and** depth-first search**(DFS).

Breadth-first search

With BFS we visit nodes level-by-level. We explore the breadth, i.e., full width of the tree at a given level, before going deeper.

BFS example

Usually, we’ll encounter binary tree, so we implement the breadth-first search using binary tree in the following examples.

#algorithms #tree-traversal #data-structures #trees #javascript

Tree Traversal in JavaScript
6.20 GEEK