Skip to main content

Depth-first Search

It is a search algorithm for traversal the tree data structure. There are three types of Depth Search to collect each values of tree.

Preorder

This type of traversal will collect the node value as long as we execute the node


function preOrderDepthTraversal(node, array){
if (!node){
return array
}

array.push(node.value)

preOrderDepthTraversal(node.left, array)

preOrderDepthTraversal(node.right, array)

return array
}

Inorder

This type of traversal will collect the node value from the left button up and right. The final array will in order from smallest to largest.


function preOrderDepthTraversal(node, array){
if (!node){
return array
}

preOrderDepthTraversal(node.left, array)

array.push(node.value)

preOrderDepthTraversal(node.right, array)

return array
}

Postorder

This type of traversal will collect the children from the left and then go up.


function preOrderDepthTraversal(node, array){
if (!node){
return array
}

preOrderDepthTraversal(node.left, array)

preOrderDepthTraversal(node.right, array)

array.push(node.value)

return array
}