Binary Tree — BFS, DFS — JavaScript

Binary Tree

The binary tree is a tree data structure in which each node has two children, which are referred to as the left child and the right child.

There are two search techniques in a binary tree,

• Depth-First Search (DFS)

In BFS, all nodes in each level (horizontally) should be visited before to go next level.

Algorithm

1. Initialize
• queue with root node
• bfsValues — [] — to hold result values
• tempNode

2. do below while queue length > 0

• pop queue and load into tempNode
• Add tempNode value into bfsValues
• check tempNode left node, if node exists, add to queue
• check tempNode right node, if node exists, add to queue

Depth-First Search (DFS)

In DFS, all nodes in each level (vertically) should be visited before to go next level.

Algorithm

1. Initialize
• stack with root node
• dfsValues — [] — to hold result values
• tempNode

2. do below while stack length > 0

• shift stack and load into tempNode
• Add tempNode value into dfsValues
• check tempNode right node, if node exists, add to the stack
• check tempNode left node, if node exists, add to the stack
{"ft_lang_label":"__label__en","ft_lang_prob":0.70549726,"math_prob":0.5041044,"size":1363,"snap":"2022-05-2022-21","text_gpt3_token_len":346,"char_repetition_ratio":0.13097866,"word_repetition_ratio":0.32921812,"special_character_ratio":0.23771094,"punctuation_ratio":0.08835341,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9782317,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-01-26T10:24:04Z\",\"WARC-Record-ID\":\"<urn:uuid:62b73c36-5089-4f25-95f5-ea2b7f08e34c>\",\"Content-Length\":\"131676\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:23bed52e-ff69-40ba-9908-805065e872c4>\",\"WARC-Concurrent-To\":\"<urn:uuid:725d3080-82be-497c-baa8-46a91ba09a8b>\",\"WARC-IP-Address\":\"162.159.152.4\",\"WARC-Target-URI\":\"https://ungalganeshtech.medium.com/binary-tree-bfs-dfs-javascript-73a170ecaea3?source=post_internal_links---------5-------------------------------\",\"WARC-Payload-Digest\":\"sha1:JO54NRVFUUZBIIHYN5DQ6MOLD2KHH43Y\",\"WARC-Block-Digest\":\"sha1:FSCUWTDXHZ4C3QRZBVEGUYTHAC5K7N3Q\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-05/CC-MAIN-2022-05_segments_1642320304947.93_warc_CC-MAIN-20220126101419-20220126131419-00208.warc.gz\"}"}