DEV Community

Cover image for Elementary Data Structures with JavaScript - Binary trees - PART 3๐Ÿš€
devlazar
devlazar

Posted on

4 2

Elementary Data Structures with JavaScript - Binary trees - PART 3๐Ÿš€

Table Of Contents
* ๐Ÿค“ INTRODUCTION
* ๐ŸŒดBREADTH-FIRST SEARCH
* ๐ŸŒŠDEPTH-FIRST SEARCH
* ๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ปCODE
* ๐Ÿ™ THANK YOU

๐Ÿค“ INTRODUCTION

Hello, my dear coders! I hope you are all having a great day ๐Ÿš€
Today, we are going to explore ways to traverse a tree with algorithms designed to optimize the search and traversal. Of course, for our implementation, we will use Vanilla JavaScript.

If you missed the previous part of this article you can check it out right here:

Please feel free to connect with me via Twitter, Instagram or LinkedIn

๐ŸŒด BREADTH-FIRST SEARCH

Breadth-first search is characterized by the fact that it focuses on every item, from left to right, on every level before moving to the next.
Alt Text

๐ŸŒŠ DEPTH-FIRST SEARCH

The strategy followed by depth-first search is, as its name implies, to search โ€œdeeperโ€ in the three whenever possible. Depth-first searches are more concerned with completing a traversal down the whole side of the tree to the leaves than completing every level. There are three main ways to handle this, preOrder, postOrder, and inOrder but theyโ€™re just very slight modifications of each other to change the output order.

1๏ธโƒฃ PREORDER

What preorder does, it processes the root, traverses the left subtree, and after that, traverses the right subtree.

Alt Text

2๏ธโƒฃ POSTORDER

First, we traverse the left subtree, after that, traverse the right subtree and, process the root.
Alt Text

3๏ธโƒฃ INORDER

First, we traverse the left subtree of the root, then we process the root and after that, we traverse the right subtree of the root.
Alt Text

๐Ÿ‘จ๐Ÿปโ€๐Ÿ’ป CODE

Here is the code! ๐Ÿš€

๐Ÿ™ THANK YOU FOR READING!

References:
School notes...
School books...

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!

โ˜• SUPPORT ME AND KEEP ME FOCUSED!
Buy Me a Coffee at ko-fi.com

Have a nice time hacking! ๐Ÿ˜Š

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post โ†’

Top comments (0)