Binary Tree | Set 1 (Introduction) - GeeksforGeeks

22 Nov, 2021
Trees: Unlike Arrays, Linked Lists, Stack and queues, which are linear data structures, trees are hierarchical data structures.Tree Vocabulary: The topmost node is called root of the tree. The elements that are directly under an element are called its children. The element directly above something is called its parent. For example, ‘a’ is a child of ‘f’, and ‘f’ is the parent of ‘a’. Finally, elements with no children are called leaves. 
      tree
      ----
       j    <-- root
     /   \
    f      k  
  /   \      \
 a     h      z    <-- leaves
Why Trees? 1. One reason to use trees might be because you want to store information that naturally forms a hierarchy. For example, the file system on a computer: 
file system
-----------
     /    <-- root
  /      \
...       home
      /          \
   ugrad        course
    /       /      |     \
  ...      cs101  cs112  cs113
2. Trees (with some ordering e.g., BST) provide moderate access/search (quicker than Linked List and slower than arrays). 3. Trees provide moderate insertion/deletion (quicker than Arrays and slower than Unordered Linked Lists). 4. Like Linked Lists and unlike Arrays, Trees don’t have an upper limit on number of nodes as nodes are linked using pointers.Main applications of trees include: 1. Manipulate hierarchical data. 2. Make information easy to search (see tree traversal). 3. Manipulate sorted lists of data. 4. As a workflow for compositing digital images for visual effects. 5. Router algorithms 6. Form of a multi-stage decision-making (see business chess). Binary Tree: A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child. Binary Tree Representation in C: A tree is represented by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL. A Tree node contains following parts. 1. Data 2. Pointer to left child 3. Pointer to right childIn C, we can represent a tree node using structures. Below is an example of a tree node with an integer data.
C++
Python
Java
C#
Javascript
struct node{    int data;    struct node* left;    struct node* right;};
# A Python class that represents an individual node# in a Binary Treeclass Node:    def __init__(self,key):        self.left = None        self.right = None        self.val = key
/* Class containing left and right child of current   node and key value*/class Node{    int key;    Node left, right;     public Node(int item)    {        key = item;        left = right = null;    }}
/* Class containing left and right childof current node and key value*/class Node{    int key;    Node left, right;     public Node(int item)    {        key = item;        left = right = null;    }}
<script>/* Class containing left and right child of current   node and key value*/class Node{    constructor(item)    {        this.key = item;        this.left = this.right = null;    }} // This code is contributed by umadevi9616</script>
First Simple Tree in C Let us create a simple tree with 4 nodes in C. The created tree would be as following.  
      tree
      ----
       1    <-- root
     /   \
    2     3  
   /   
  4
C++
C
Java
Python
C#
Javascript
#include <bits/stdc++.h>using namespace std; struct Node {    int data;    struct Node* left;    struct Node* right;     // val is the key or the value that    // has to be added to the data part    Node(int val)    {        data = val;         // Left and right child for node        // will be initialized to null        left = NULL;        right = NULL;    }}; int main(){     /*create root*/    struct Node* root = new Node(1);    /* following is the tree after above statement              1            / \          NULL NULL    */     root->left = new Node(2);    root->right = new Node(3);    /* 2 and 3 become left and right children of 1                    1                  /    \                 2       3               /  \     /  \            NULL NULL  NULL NULL    */     root->left->left = new Node(4);    /* 4 becomes left child of 2               1            /     \           2       3          / \     / \         4  NULL NULL NULL        / \     NULL NULL    */     return 0;}
#include <stdio.h>#include <stdlib.h>struct node {    int data;    struct node* left;    struct node* right;}; /* newNode() allocates a new nodewith the given data and NULL leftand right pointers. */struct node* newNode(int data){    // Allocate memory for new node    struct node* node        = (struct node*)malloc(sizeof(struct node));     // Assign data to this node    node->data = data;     // Initialize left and    // right children as NULL    node->left = NULL;    node->right = NULL;    return (node);} int main(){    /*create root*/    struct node* root = newNode(1);    /* following is the tree after above statement         1        / \      NULL NULL    */     root->left = newNode(2);    root->right = newNode(3);    /* 2 and 3 become left and right children of 1            1         /    \        2      3      /  \    /  \   NULL NULL NULL NULL    */     root->left->left = newNode(4);    /* 4 becomes left child of 2             1         /    \        2      3      /  \    /  \     4 NULL NULL NULL    / \ NULL NULL    */     getchar();    return 0;}
/* Class containing left and right child of current   node and key value*/class Node{    int key;    Node left, right;     public Node(int item)    {        key = item;        left = right = null;    }} // A Java program to introduce Binary Treeclass BinaryTree{    // Root of Binary Tree    Node root;     // Constructors    BinaryTree(int key)    {        root = new Node(key);    }     BinaryTree()    {        root = null;    }     public static void main(String[] args)    {        BinaryTree tree = new BinaryTree();         /*create root*/        tree.root = new Node(1);         /* following is the tree after above statement               1            /   \          null  null     */         tree.root.left = new Node(2);        tree.root.right = new Node(3);         /* 2 and 3 become left and right children of 1               1            /     \          2        3        /   \     /  \      null null null null  */          tree.root.left.left = new Node(4);        /* 4 becomes left child of 2                    1                /       \               2          3             /   \       /  \            4    null  null  null           /   \          null null         */    }}
# Python program to introduce Binary Tree # A class that represents an individual node in a# Binary Treeclass Node:    def __init__(self,key):        self.left = None        self.right = None        self.val = key  # create rootroot = Node(1)''' following is the tree after above statement        1      /   \     None  None''' root.left      = Node(2);root.right     = Node(3);   ''' 2 and 3 become left and right children of 1           1         /   \        2      3     /    \    /  \   None None None None'''  root.left.left  = Node(4);'''4 becomes left child of 2           1       /       \      2          3    /   \       /  \   4    None  None  None  /  \None None'''
// A C# program to introduce Binary Treeusing System; /* Class containing left and right childof current node and key value*/public class Node{    public int key;    public Node left, right;     public Node(int item)    {        key = item;        left = right = null;    }} public class BinaryTree{    // Root of Binary Tree    Node root;     // Constructors    BinaryTree(int key)    {        root = new Node(key);    }     BinaryTree()    {        root = null;    }     // Driver Code    public static void Main(String[] args)    {        BinaryTree tree = new BinaryTree();         /*create root*/        tree.root = new Node(1);         /* following is the tree after above statement              1            / \         null null     */        tree.root.left = new Node(2);        tree.root.right = new Node(3);         /* 2 and 3 become left and right children of 1                1             /     \           2        3         /  \     /   \       null null null null */        tree.root.left.left = new Node(4);                 /* 4 becomes left child of 2                1             /     \           2        3         /  \     /   \         4 null null null        / \     null null        */    }} // This code is contributed by PrinciRaj1992
<script>/* Class containing left and right child of current   node and key value*/ class Node {        constructor(val) {            this.key = val;            this.left = null;            this.right = null;        }    }   // A javascript program to introduce Binary Tree     // Root of Binary Tree    var root = null;               /*create root*/        root = new Node(1);         /* following is the tree after above statement               1            /   \          null  null     */         root.left = new Node(2);        root.right = new Node(3);         /* 2 and 3 become left and right children of 1               1            /     \          2        3        /   \     /  \      null null null null  */           root.left.left = new Node(4);        /* 4 becomes left child of 2                    1                /       \               2          3             /   \       /  \            4    null  null  null           /   \          null null         */  // This code contributed by umadevi9616</script>
Summary: Tree is a hierarchical data structure. Main uses of trees include maintaining hierarchical data, providing moderate access and insert/delete operations. Binary trees are special cases of tree where every node has at most two children. https://youtu.be/W6aZKAJcNJABelow are set 2 and set 3 of this post. Properties of Binary Tree Types of Binary TreePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nsp92
princiraj1992
manikanta2901
Twinkl Bajaj
anandpatel98260
umadevi9616
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Write a Program to Find the Maximum Depth or Height of a Tree
A program to check if a binary tree is BST or not
Decision Tree
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
BFS vs DFS for Binary Tree
Binary Tree (Array implementation)