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.
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 2ˡ 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:
#data-structures #golang #programming