Binary Tree

A tree is a hierarchical data structure which consists of a set of nodes. A tree is a graph with no cycles. 

Binary Tree is a special type of tree, in which each node can only have a maximum of 2 children.

In Binary Tree each node consists of : 

1. Data
2. Pointer to left node
3. Pointer to right node


TREE TERMINOLOGY : 

Root
- Node with no parent, only one in a tree

Leaf
- Any node with no children

Parent 
- If a node is directly above node x, then it is parent of node x

Child 
- If a node is directly below node x, then it is child of node x

Ancestor 
- If a node is in the path from root to node x, then is ancestor of node x

Descendant 
- If a node y is ancestor of node x, then node x is descendant of node y

Siblings
-Set of nodes that have the same parent node





A Binary Tree can be implemented in C++ as :
 #include <iostream>  
 using namespace std;  
 // Implementation of Binary Tree in C++  
 struct tree{  
      int data;  
      struct tree * left;  
      struct tree * right;  
 };  
 int main()  
 {            
      struct tree *root;  
      struct tree A;  
      struct tree B;  
      struct tree C;  
      root = &A;  
      root->left = &B;  
      root->right = &C;  
      root->data = 10;  
      B.data = 20;  
      C.data = 30;  
      cout<<A.data<<endl;     // 10  
      cout<<root->left->data<<endl; // 20  
      cout<<root->right->data<<endl; // 30  
 }  

The binary tree implemented by the program above would look like : 

Height of tree :

If the tree contains no nodes, its height is 0.
Otherwise, it 1 + height of taller subtree. [1 is for root and take max(left,right)]

The height of the tree above is 2. 

Level of node :

The level of node n is the number of nodes on the path from root to node n.

For root, level is 1. For every other node it is 1 + level of its parent

Some properties :

1. Maximum number of nodes in a binary tree of height h is ((2^h)-1)
2. Maximum number of nodes at level I of a binary tree is (2^(I-1))
3. In binary tree, number of leaf nodes is always one more than nodes with two children.



Comments

Popular posts from this blog

In Place Algorithms

References in C++