A binary tree is a data structure where every node has at most two child nodes. Below is a sample binary tree. The top most node is the root node.

All nodes at the bottom that do not have any child nodes attached are known as leaf nodes.

Image for post

A simple binary tree

If a binary tree is of height h, then there can be maximum 2⁽ ʰ⁺ ¹⁾-1 nodes. Let n be the number of nodes. Then :

=> n = 2⁽ ʰ⁺ ¹⁾-1

=> n + 1 = 2⁽ ʰ⁺ ¹⁾

=> log₂(n+1) = log₂(2⁽ ʰ⁺ ¹⁾)

=> log₂(n+1)(h+1)log₂2

=> log₂(n+1) -1 = h or h = log₂(n+1) -1

So given n nodes the optimal height h of a tree is log₂(n+1) -1

The root node is at level 0. At every level there can be maximum  nodes, where _l _is the level.

Enough of mathematics! Now let me explain binary search tree. A binary search tree is a special data structure where data in left child is less than its parent node and right child is greater than its parent. Below is an example of a binary search tree:

Image for post

#data-structures #golang #programming

Binary Search Tree Traversal (in-order, pre-order and post-order) in Go
1.55 GEEK