SlideShare ist ein Scribd-Unternehmen logo
1 von 39
Trees
    EENG212
    Algorithms
           and
Data Structures
Trees
Outline
 Introduction to Trees
 Binary Trees: Basic Definitions

 Traversing Binary Trees

 Node Representation of Binary Trees

 Primitive Functions in Binary Trees
Introduction to Trees
BINARY TREES: BASIC DEFINITIONS
 A binary tree is a finite set of elements that are
  either empty or is partitioned into three disjoint
  subsets. The first subset contains a single element
  called the root of the tree. The other two subsets
  are themselves binary trees called the left and right
  subtrees of the original tree. A left or right subtree
  can be empty.
 Each element of a binary tree is called a node of the
  tree. The following figure shows a binary tree with 9
  nodes where A is the root.
BINARY TREES: BASIC
DEFINITIONS
                root

left subtree
                       right subtree
BINARY TREES: BASIC
DEFINITIONS
   If A is the root of a binary tree and B is the root of its
    left or right subtrees, then A is said to be the father
    of B and B is said to be the left son of A.
   A node that has no sons is called the leaf.
   Node n1 is the ancestor of node n2 if n1 is either
    the father of n2 or the father of some ancestor of n2.
    In such a case n2 is a descendant of n1.
   Two nodes are brothers if they are left and right
    sons of the same father.
BINARY TREES: BASIC
DEFINITIONS


left son            right son




           leaves
BINARY TREES: BASIC
DEFINITIONS
   If every nonleaf node in a binary tree has
    nonempty left and right subtrees, the tree is
    called a strictly binary tree.
BINARY TREES: BASIC
DEFINITIONS
   The level of a node in a binary tree is defined
    as follows: The root of the tree has level 0,
    and the level of any other node in the tree is
    one more than the level of its father.
   The depth of a binary tree is the maximum
    level of any leaf in the tree.
   A complete binary tree of depth d is the
    strictly binary all of whose leaves are at level
    d. A complete binary tree with depth d has 2d
    leaves and 2d-1 nonleaf nodes.
BINARY TREES: BASIC
DEFINITIONS
TRAVERSING BINARY TREES
   One of the common operations of a binary tree is to
    traverse the tree. Traversing a tree is to pass
    through all of its nodes once. You may want to print
    the contents of each node or to process the
    contents of the nodes. In either case each node of
    the tree is visited.
   There are three main traversal methods where
    traversing a binary tree involves visiting the root and
    traversing its left and right subtrees. The only
    difference among these three methods is the order
    in which these three operations are performed.
TRAVERSING BINARY TREES
   Traversing a binary tree in preorder
    (depth-first order)
    1. Visit the root.
    2. Traverse the left subtree in preorder.
    3. Traverse the right subtree in preorder.
Traversing a binary tree in
preorder




          Preorder: ABDGCEHIF
TRAVERSING BINARY TREES
Traversing a binary tree in inorder
(or symmetric order)
  1. Traverse the left subtree in inorder.
  2. Visit the root.
  3. Traverse the right subtree in inorder.
Traversing a binary tree in
inorder




         Inorder: DGBAHEICF
TRAVERSING BINARY TREES
   Traversing a binary tree in postorder
    1. Traverse the left subtree in postorder.
    2. Traverse the right subtree in
      postorder.
    3. Visit the root.
Traversing a binary tree in
postorder




         Postorder: GDBHIEFCA
NODE REPRESENTATION OF
BINARY TREES
   Each node in a binary tree contains info, left, right
    and father fields. The left, right and father fields
    points the node’s left son, right son and the father
    respectively.

    struct node{
       int info; /* can be of different type*/
       struct node *left;
       struct node *right;
       struct node *father;
    };
    typedef struct node *NODEPTR;
PRIMITIVE FUNCTIONS IN
BINARY TREES
 The maketree function allocates a node and
 sets it as the root of a single node binary tree.
 NODEPTR maketree(int x)
 {
 NODEPTR p;
 p = getnode();
 p->info = x;
 p->left = NULL;
 p->right = NULL;
 return p;
 }
PRIMITIVE FUNCTIONS IN
BINARY TREES
   The setleft and setright functions sets a node with
    content x as the left son and right son of the node p
    respectively.
void setleft(NODEPTR p, int x)   void setright(NODEPTR p, int x)
{                                {
if(p == NULL){                   if(p == NULL){
printf(“void insertionn”);      printf(“void insertionn”);
else if (p->left != NULL)        else if (p->right != NULL)
printf(“invalid insertionn”);   printf(“invalid insertionn”);
else                             else
p->left = maketree(x);           p->right = maketree(x);
}                                }
BINARY TREE TRAVERSAL
METHODS
   Recursive functions can be used to perform
    traversal on a given binary tree. Assume that
    dynamic node representation is used for a given
    binary tree.
   In the following traversal methods, the tree is
    traversed always in downward directions. Therefore
    the father field is not needed.
   The following recursive preorder traversal function
    displays the info part of the nodes in preorder. Note
    that the info part is integer number and tree is a
    pointer to the root of the tree.
BINARY TREE TRAVERSAL
METHODS
void pretrav(NODEPTR tree)
{
if(tree != NULL){
    printf(“%dn”, tree->info);
    pretrav(tree->left);
    pretrav(tree->right);
}
}
BINARY TREE TRAVERSAL
METHODS
   The following recursive inorder traversal
    function displays the info part of the nodes in
    inorder.
   Note that the info part is integer number and
    tree is a pointer to the root of the tree.
BINARY TREE TRAVERSAL
METHODS
void intrav(NODEPTR tree)
{
if(tree != NULL){
    intrav(tree->left);
    printf(“%dn”, tree->info);
    intrav(tree->right);
}
}
BINARY TREE TRAVERSAL
METHODS
   The following recursive postorder traversal
    function displays the info part of the nodes in
    postorder.
   Note that the info part is integer number and
    tree is a pointer to the root of the tree.
BINARY TREE TRAVERSAL
METHODS
void posttrav(NODEPTR tree)
{
if(tree != NULL){
    posttrav(tree->left);
    posttrav(tree->right);
    printf(“%dn”, tree->info);
}
}
BINARY SEARCH TREE: AN
APPLICATION OF BINARY TREES
   A binary tree, that has the property that all
    elements in the left subtree of a node n are
    less than the contents of n, and all elements
    in the right subtree of n are greater than or
    equal to the contents of n, is called a Binary
    Search Tree or Ordered Binary Tree.
BINARY SEARCH TREE: AN
APPLICATION OF BINARY TREES
 Given the following sequence of numbers,
 14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5
 The following binary search tree can be
  constructed.
BINARY SEARCH TREE: AN
APPLICATION OF BINARY TREES
BINARY SEARCH TREE: AN
APPLICATION OF BINARY TREES
 The inorder (left-root-right) traversal of the
  above Binary Search Tree and printing the
  info part of the nodes gives the sorted
  sequence in ascending order. Therefore,
  the Binary search tree approach can easily
  be used to sort a given array of numbers.
 The inorder traversal on the above Binary
  Search Tree is:
 3, 4, 4, 5, 5, 7, 9, 9, 14, 14, 15, 16, 17, 18, 20
SEARCHING THROUGH THE
BINARY SEARCH TREE
   Searching operation of the binary search tree
    is always in downward direction. Therefore
    the following node structure can be used to
    represent the node of a given binary search
    tree.
   Note that the father link is not required.
SEARCHING THROUGH THE
BINARY SEARCH TREE
struct node{
 int info; /* can be of different type*/
 struct node *left;
 struct node *right;
};
typedef struct node *NODEPTR;
SEARCHING THROUGH THE
BINARY SEARCH TREE
   The following recursive function can be used
    to search for a given key element in a given
    array of integers. The array elements are
    stored in a binary search tree. Note that the
    function returns TRUE (1) if the searched key
    is a member of the array and FALSE (0) if the
    searched key is not a member of the array.
SEARCHING THROUGH THE
BINARY SEARCH TREE
int BinSearch(NODEPTR p, int key)
{
if(p == NULL)
    return FALSE;
else {
if (key == p->info)
    return TRUE;
else{
if(key < p->info)
    return BinSearch(p->left, key);
else
    return BinSearch(p->right, key);
}
}
}
INSERTING NODES INTO A
BINARY SEARCH TREE
   The following recursive function can be used
    to insert a new node into a given binary
    search tree.
NODEPTR insert(NODEPTR p, int x)
{
if(p == NULL){
    p = getnode();
    p->info = x;
    p->left = NULL;
    p->right = NULL;
    return p;
}
else{
    if(x < p->info)
        p->left = insert(p->left, x);
    else
        p->right = insert(p->right, x);
    return p;
}
}
Application of Binary Search
Tree
   Suppose that we wanted to find all duplicates in a list of
    numbers. One way of doing this to compare each number with all
    those that precede it. However this involves a large number of
    comparison. The number of comparison can be reduced by using
    a binary tree. The first number in the list is placed in a node that
    is the root of the binary tree with empty left and right sub-trees.
    The other numbers in the list is than compared to the number in
    the root. If it is matches, we have duplicate. If it is smaller, we
    examine the left sub-tree; if it is larger we examine the right sub-
    tree. If the sub-tree is empty, the number is not a duplicate and is
    placed into a new node at that position in the tree. If the sub-tree
    is nonempty, we compare the number to the contents of the root
    of the sub-tree and the entire process is repeated with the sub-
    tree. A program for doing this follows .
#include <stdio.h>
#include <stdlib.h>
struct node {
           struct node *left ;
           int info ;
           struct node *right;
           };
typedef struct node *NODEPTR;
NODEPTR maketree(int);
NODEPTR getnode(void);
void intrav(NODEPTR);
void main()
{
int number;
NODEPTR root , p , q;
  printf("%sn","Enter First number");
  scanf("%d",&number);
  root=maketree(number); /* insert first root item */
   printf("%sn","Enter the other numbers");
while(scanf("%d",&number) !=EOF)
 { p=q=root;
   /* find insertion point */
   while((number !=p->info) && q!=NULL)
    {p=q;
      if (number <p->info)
                          q = p->left;
                          else
                          q = p->right;
   }
   q=maketree(number);
   /* insertion */
   if (number==p->info)
                         printf("%d is a duplicate n",number);
                         else if (number<p->info)
                               p->left=q;
                                                   else p->right=q;
 }
  printf("Tree Created n ");
  /* inorder Traversing */
  intrav(root);
 }
void intrav(NODEPTR tree)
{
if(tree != NULL){
      intrav(tree->left);
      printf(“%dn”, tree->info);
      intrav(tree->right);
}
}
NODEPTR maketree(int x)
{
NODEPTR p;
p = getnode();
p->info = x;
p->left = NULL;
p->right = NULL;
return p;
}
NODEPTR getnode(void)
{
 NODEPTR p;
p=(NODEPTR) malloc(sizeof(struct node));
return p;
}

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Trees
TreesTrees
Trees
 
Data Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary TreeData Structure and Algorithms Binary Tree
Data Structure and Algorithms Binary Tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Lecture 5 trees
Lecture 5 treesLecture 5 trees
Lecture 5 trees
 
Avl trees
Avl treesAvl trees
Avl trees
 
Tree
TreeTree
Tree
 
Binary trees
Binary treesBinary trees
Binary trees
 
Trees in Data Structure
Trees in Data StructureTrees in Data Structure
Trees in Data Structure
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Binary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red BlackBinary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red Black
 
Avl trees
Avl treesAvl trees
Avl trees
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
 
1.1 binary tree
1.1 binary tree1.1 binary tree
1.1 binary tree
 
data structure(tree operations)
data structure(tree operations)data structure(tree operations)
data structure(tree operations)
 

Ähnlich wie Trees (20)

Data Structures
Data StructuresData Structures
Data Structures
 
VCE Unit 05.pptx
VCE Unit 05.pptxVCE Unit 05.pptx
VCE Unit 05.pptx
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Trees in data structrures
Trees in data structruresTrees in data structrures
Trees in data structrures
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
Dsc++ unit 3 notes
Dsc++ unit 3 notesDsc++ unit 3 notes
Dsc++ unit 3 notes
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptxNON-LINEAR DATA STRUCTURE-TREES.pptx
NON-LINEAR DATA STRUCTURE-TREES.pptx
 
Unit iv data structure-converted
Unit  iv data structure-convertedUnit  iv data structure-converted
Unit iv data structure-converted
 
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptxTREE DATA STRUCTURE SLIDES dsa dsa .pptx
TREE DATA STRUCTURE SLIDES dsa dsa .pptx
 
Tree
TreeTree
Tree
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
 
Lecture 5 tree.pptx
Lecture 5 tree.pptxLecture 5 tree.pptx
Lecture 5 tree.pptx
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
Binary tree and operations
Binary tree and operations Binary tree and operations
Binary tree and operations
 
Tree
TreeTree
Tree
 
Trees.pptx
Trees.pptxTrees.pptx
Trees.pptx
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Binary tree
Binary  treeBinary  tree
Binary tree
 

Kürzlich hochgeladen

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinojohnmickonozaleda
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 

Kürzlich hochgeladen (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
FILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipinoFILIPINO PSYCHology sikolohiyang pilipino
FILIPINO PSYCHology sikolohiyang pilipino
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 

Trees

  • 1. Trees EENG212 Algorithms and Data Structures
  • 2. Trees Outline  Introduction to Trees  Binary Trees: Basic Definitions  Traversing Binary Trees  Node Representation of Binary Trees  Primitive Functions in Binary Trees
  • 3. Introduction to Trees BINARY TREES: BASIC DEFINITIONS  A binary tree is a finite set of elements that are either empty or is partitioned into three disjoint subsets. The first subset contains a single element called the root of the tree. The other two subsets are themselves binary trees called the left and right subtrees of the original tree. A left or right subtree can be empty.  Each element of a binary tree is called a node of the tree. The following figure shows a binary tree with 9 nodes where A is the root.
  • 4. BINARY TREES: BASIC DEFINITIONS root left subtree right subtree
  • 5. BINARY TREES: BASIC DEFINITIONS  If A is the root of a binary tree and B is the root of its left or right subtrees, then A is said to be the father of B and B is said to be the left son of A.  A node that has no sons is called the leaf.  Node n1 is the ancestor of node n2 if n1 is either the father of n2 or the father of some ancestor of n2. In such a case n2 is a descendant of n1.  Two nodes are brothers if they are left and right sons of the same father.
  • 7. BINARY TREES: BASIC DEFINITIONS  If every nonleaf node in a binary tree has nonempty left and right subtrees, the tree is called a strictly binary tree.
  • 8. BINARY TREES: BASIC DEFINITIONS  The level of a node in a binary tree is defined as follows: The root of the tree has level 0, and the level of any other node in the tree is one more than the level of its father.  The depth of a binary tree is the maximum level of any leaf in the tree.  A complete binary tree of depth d is the strictly binary all of whose leaves are at level d. A complete binary tree with depth d has 2d leaves and 2d-1 nonleaf nodes.
  • 10. TRAVERSING BINARY TREES  One of the common operations of a binary tree is to traverse the tree. Traversing a tree is to pass through all of its nodes once. You may want to print the contents of each node or to process the contents of the nodes. In either case each node of the tree is visited.  There are three main traversal methods where traversing a binary tree involves visiting the root and traversing its left and right subtrees. The only difference among these three methods is the order in which these three operations are performed.
  • 11. TRAVERSING BINARY TREES  Traversing a binary tree in preorder (depth-first order) 1. Visit the root. 2. Traverse the left subtree in preorder. 3. Traverse the right subtree in preorder.
  • 12. Traversing a binary tree in preorder Preorder: ABDGCEHIF
  • 13. TRAVERSING BINARY TREES Traversing a binary tree in inorder (or symmetric order) 1. Traverse the left subtree in inorder. 2. Visit the root. 3. Traverse the right subtree in inorder.
  • 14. Traversing a binary tree in inorder Inorder: DGBAHEICF
  • 15. TRAVERSING BINARY TREES  Traversing a binary tree in postorder 1. Traverse the left subtree in postorder. 2. Traverse the right subtree in postorder. 3. Visit the root.
  • 16. Traversing a binary tree in postorder Postorder: GDBHIEFCA
  • 17. NODE REPRESENTATION OF BINARY TREES  Each node in a binary tree contains info, left, right and father fields. The left, right and father fields points the node’s left son, right son and the father respectively. struct node{ int info; /* can be of different type*/ struct node *left; struct node *right; struct node *father; }; typedef struct node *NODEPTR;
  • 18. PRIMITIVE FUNCTIONS IN BINARY TREES The maketree function allocates a node and sets it as the root of a single node binary tree. NODEPTR maketree(int x) { NODEPTR p; p = getnode(); p->info = x; p->left = NULL; p->right = NULL; return p; }
  • 19. PRIMITIVE FUNCTIONS IN BINARY TREES  The setleft and setright functions sets a node with content x as the left son and right son of the node p respectively. void setleft(NODEPTR p, int x) void setright(NODEPTR p, int x) { { if(p == NULL){ if(p == NULL){ printf(“void insertionn”); printf(“void insertionn”); else if (p->left != NULL) else if (p->right != NULL) printf(“invalid insertionn”); printf(“invalid insertionn”); else else p->left = maketree(x); p->right = maketree(x); } }
  • 20. BINARY TREE TRAVERSAL METHODS  Recursive functions can be used to perform traversal on a given binary tree. Assume that dynamic node representation is used for a given binary tree.  In the following traversal methods, the tree is traversed always in downward directions. Therefore the father field is not needed.  The following recursive preorder traversal function displays the info part of the nodes in preorder. Note that the info part is integer number and tree is a pointer to the root of the tree.
  • 21. BINARY TREE TRAVERSAL METHODS void pretrav(NODEPTR tree) { if(tree != NULL){ printf(“%dn”, tree->info); pretrav(tree->left); pretrav(tree->right); } }
  • 22. BINARY TREE TRAVERSAL METHODS  The following recursive inorder traversal function displays the info part of the nodes in inorder.  Note that the info part is integer number and tree is a pointer to the root of the tree.
  • 23. BINARY TREE TRAVERSAL METHODS void intrav(NODEPTR tree) { if(tree != NULL){ intrav(tree->left); printf(“%dn”, tree->info); intrav(tree->right); } }
  • 24. BINARY TREE TRAVERSAL METHODS  The following recursive postorder traversal function displays the info part of the nodes in postorder.  Note that the info part is integer number and tree is a pointer to the root of the tree.
  • 25. BINARY TREE TRAVERSAL METHODS void posttrav(NODEPTR tree) { if(tree != NULL){ posttrav(tree->left); posttrav(tree->right); printf(“%dn”, tree->info); } }
  • 26. BINARY SEARCH TREE: AN APPLICATION OF BINARY TREES  A binary tree, that has the property that all elements in the left subtree of a node n are less than the contents of n, and all elements in the right subtree of n are greater than or equal to the contents of n, is called a Binary Search Tree or Ordered Binary Tree.
  • 27. BINARY SEARCH TREE: AN APPLICATION OF BINARY TREES  Given the following sequence of numbers, 14, 15, 4, 9, 7, 18, 3, 5, 16, 4, 20, 17, 9, 14, 5  The following binary search tree can be constructed.
  • 28. BINARY SEARCH TREE: AN APPLICATION OF BINARY TREES
  • 29. BINARY SEARCH TREE: AN APPLICATION OF BINARY TREES  The inorder (left-root-right) traversal of the above Binary Search Tree and printing the info part of the nodes gives the sorted sequence in ascending order. Therefore, the Binary search tree approach can easily be used to sort a given array of numbers.  The inorder traversal on the above Binary Search Tree is: 3, 4, 4, 5, 5, 7, 9, 9, 14, 14, 15, 16, 17, 18, 20
  • 30. SEARCHING THROUGH THE BINARY SEARCH TREE  Searching operation of the binary search tree is always in downward direction. Therefore the following node structure can be used to represent the node of a given binary search tree.  Note that the father link is not required.
  • 31. SEARCHING THROUGH THE BINARY SEARCH TREE struct node{ int info; /* can be of different type*/ struct node *left; struct node *right; }; typedef struct node *NODEPTR;
  • 32. SEARCHING THROUGH THE BINARY SEARCH TREE  The following recursive function can be used to search for a given key element in a given array of integers. The array elements are stored in a binary search tree. Note that the function returns TRUE (1) if the searched key is a member of the array and FALSE (0) if the searched key is not a member of the array.
  • 33. SEARCHING THROUGH THE BINARY SEARCH TREE int BinSearch(NODEPTR p, int key) { if(p == NULL) return FALSE; else { if (key == p->info) return TRUE; else{ if(key < p->info) return BinSearch(p->left, key); else return BinSearch(p->right, key); } } }
  • 34. INSERTING NODES INTO A BINARY SEARCH TREE  The following recursive function can be used to insert a new node into a given binary search tree.
  • 35. NODEPTR insert(NODEPTR p, int x) { if(p == NULL){ p = getnode(); p->info = x; p->left = NULL; p->right = NULL; return p; } else{ if(x < p->info) p->left = insert(p->left, x); else p->right = insert(p->right, x); return p; } }
  • 36. Application of Binary Search Tree  Suppose that we wanted to find all duplicates in a list of numbers. One way of doing this to compare each number with all those that precede it. However this involves a large number of comparison. The number of comparison can be reduced by using a binary tree. The first number in the list is placed in a node that is the root of the binary tree with empty left and right sub-trees. The other numbers in the list is than compared to the number in the root. If it is matches, we have duplicate. If it is smaller, we examine the left sub-tree; if it is larger we examine the right sub- tree. If the sub-tree is empty, the number is not a duplicate and is placed into a new node at that position in the tree. If the sub-tree is nonempty, we compare the number to the contents of the root of the sub-tree and the entire process is repeated with the sub- tree. A program for doing this follows .
  • 37. #include <stdio.h> #include <stdlib.h> struct node { struct node *left ; int info ; struct node *right; }; typedef struct node *NODEPTR; NODEPTR maketree(int); NODEPTR getnode(void); void intrav(NODEPTR); void main() { int number; NODEPTR root , p , q; printf("%sn","Enter First number"); scanf("%d",&number); root=maketree(number); /* insert first root item */ printf("%sn","Enter the other numbers");
  • 38. while(scanf("%d",&number) !=EOF) { p=q=root; /* find insertion point */ while((number !=p->info) && q!=NULL) {p=q; if (number <p->info) q = p->left; else q = p->right; } q=maketree(number); /* insertion */ if (number==p->info) printf("%d is a duplicate n",number); else if (number<p->info) p->left=q; else p->right=q; } printf("Tree Created n "); /* inorder Traversing */ intrav(root); }
  • 39. void intrav(NODEPTR tree) { if(tree != NULL){ intrav(tree->left); printf(“%dn”, tree->info); intrav(tree->right); } } NODEPTR maketree(int x) { NODEPTR p; p = getnode(); p->info = x; p->left = NULL; p->right = NULL; return p; } NODEPTR getnode(void) { NODEPTR p; p=(NODEPTR) malloc(sizeof(struct node)); return p; }