SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Tree & BST

Md. Shakil Ahmed
Software Engineer
Astha it research & consultancy ltd.
Dhaka, Bangladesh
Natural Tree
Tree structure
Unix / Windows file structure
Definition of Tree
A tree is a finite set of one or more nodes
such that:
There is a specially designated node called
the root.
The remaining nodes are partitioned into
n>=0 disjoint sets T1, ..., Tn, where each of
these sets is a tree.
We call T1, ..., Tn the subtrees of the root.
Level and Depth

                                                                                 Level
node (13)
degree of a node                                                                 1
leaf (terminal)
                                             3
                                                     A       1
nonterminal                                                                      2
parent
children                       2
                                   B   2 1       C       2       3   D   2       3
sibling
degree of a tree (3)           E 3 F 3 G 31 H    I 3 J                           4
                           2      0   0       30    0                        3
ancestor
level of a node
height of a tree (4)   0   K 4 L                         0   M   4
                              0  4
Binary Tree
• Each Node can have at most 2 children.
Array Representation 1
• With in a single array.
• If root position is i then,
• Left Child in 2*i+1
• Right Child is 2*i+2
• For N level tree it needs 2^N –
  1 memory space.
• If current node is i then it’s
  parent is i/2.

    0   1    2   3   4   5    6   7    8    9   10   11   12   13   14

    2   7    5   2   6   -1   9   -1   -1   5   11   -1   -1   4    -1
Array Representation 1
• Advantage ->
1.Good in Full Or Complete
  Binary tree
• Disadvantage
1.If we use it in normal binary
  tree then it may be huge
  memory lose.
Array Representation 2
 • Use 3 Parallel Array
        0   1     2     3    4        5         6        7         8

Root    2   7     5     2    6        9         5        11        4

Left    1   3     -1    -1   6        8         -1       -1        -1

Right   2   4     5     -1   7        -1        -1       -1        -1


• If you need parent
                        0    1   2         3         4        5         6    7    8
                Root    2    7   5         2         6        9         5    11   4
                Left    1    3   -1        -1        6        8         -1   -1   -1
                Right   2    4   5         -1        7        -1        -1   -1   -1
                Parent -1 0      0         1         1        2         4    4    5
Linked Representation
typedef struct tnode *ptnode;
typedef struct tnode {
 int data;
 ptnode left, right;
};




                                       data

    left      data     right

                                left          right
Preorder Traversal (recursive version)

Linked Representation           Array Representation 2

void preorder(ptnode ptr)       void preorder(int nodeIndex)
/* preorder tree traversal */   {
{                                   printf(“%d”, root[nodeIndex]);
    if (ptr) {                      if(Left[nodeIndex]!=-1)
        printf(“%d”, ptr-           preorder(Left[nodeIndex]);
   >data);                          if(Right[nodeIndex]!=-1)
        preorder(ptr->left);        preorder(Right[nodeIndex]);
        preorder(ptr->right);   }
    }
}
Inorder Traversal (recursive version)

Linked Representation              Array Representation 2

void inorder(ptnode ptr)           void inorder(int nodeIndex)
/* inorder tree traversal */       {
{                                      if(Left[nodeIndex]!=-1)
    if (ptr) {                         inorder(Left[nodeIndex]);
        inorder(ptr->left);            printf(“%d”, root[nodeIndex]);
        printf(“%d”, ptr->data);       if(Right[nodeIndex]!=-1)
        inorder(ptr->right);           inorder(Right[nodeIndex]);
    }                              }
}
Postorder Traversal (recursive version)

Linked Representation              Array Representation 2

void postorder(ptnode ptr)         void postorder(int nodeIndex)
/* postorder tree traversal */     {
{                                      if(Left[nodeIndex]!=-1)
    if (ptr) {                         postorder(Left[nodeIndex]);
        postorder(ptr->left);          if(Right[nodeIndex]!=-1)
        postorder(ptr->right);         postorder(Right[nodeIndex]);
        printf(“%d”, ptr->data);       printf(“%d”, root[nodeIndex]);
    }                              }
}
Binary Search Tree
• All items in the left subtree are less than the
  root.
• All items in the right subtree are greater or
  equal to the root.
• Each subtree is itself a binary search tree.
Binary Search Tree




        16
Binary Search Tree

Elements => 23 18 12 20 44 52 35

1st Element


2nd Element


3rd Element
Binary Search Tree

4th Element




5th Element
Binary Search Tree

6th Element




7th Element
Binary Search Tree




        20
Binary Search Tree
//Array Representation 2      root = 0;
//Generate BST                 while(1){
int N = 0;                        if(Root[root]==value)
int Root[1000000],                    break;
   Left[1000000],                  else if(Root[root]>value)
   Right[1000000];                 {
                                     if(Left[root]!=-1)
void AddToBST(int value)             root = Left[root];
{                                    else
   if(N==0)                          {
   {                                  Root[N]=value;
      Root[N]=value;                  Left[N]=-1;
      Left[N]=-1;                     Right[N]=-1;
      Right[N]=-1;                    Left[root]=N;
   }                                  N++;
   else                               break;
   {                                 }
                                   }
Binary Search Tree
            else                    Client Code =>
            {                       scanf(“%d”,&n);
              if(Right[root]!=-1)
              root = Right[root];   for(i=0;i<n;i++)
              else                  {
              {                     scanf(“%d”,&t);
                Root[N]=value;      AddToBST(t);
                Left[N]=-1;         }
                Right[N]=-1;
                Right[root]=N;
                N++;
              break;
              }
            }
        }
    }
}
Binary Search Tree
//Array Representation 2
                                    else
//Search in BST
                                    {
int SearchInBST(int value)
                                       if(Right[root]!=-1)
{
                                       root = Right[root];
   if(N==0)
                                       else
   return -1;
                                       return -1;
                                    }
  root = 0;
                                    }
  while(1)
                                    return -1;
  {
                                }
    if(Root[root]==value)
       return root;
                                Client Code =>
    else if(Root[root]>value)
                                scanf(“%d”,&n);
    {
                                for(i=0;i<n;i++)
      if(Left[root]!=-1)
                                {
      root = Left[root];
                                   scanf(“%d”,&t);
      else
                                   Printf(“%d”,SearchInBST(t));
      return -1;
                                }
    }
Sample
LightOj =>
• http://www.lightoj.com/volume_showproble
  m.php?problem=1087
• http://www.lightoj.com/volume_showproble
  m.php?problem=1097
• http://www.lightoj.com/volume_showproble
  m.php?problem=1293
Thanks!

Weitere ähnliche Inhalte

Was ist angesagt?

Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobikrmboya
 
09 logic programming
09 logic programming09 logic programming
09 logic programmingsaru40
 
DataCamp Cheat Sheets 4 Python Users (2020)
DataCamp Cheat Sheets 4 Python Users (2020)DataCamp Cheat Sheets 4 Python Users (2020)
DataCamp Cheat Sheets 4 Python Users (2020)EMRE AKCAOGLU
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1H K
 
Banishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPBanishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPDavid Hayes
 
Prolog programming
Prolog programmingProlog programming
Prolog programmingHarry Potter
 
08 ds and algorithm session_11
08 ds and algorithm session_1108 ds and algorithm session_11
08 ds and algorithm session_11Niit Care
 
07 ds and algorithm session_10
07 ds and algorithm session_1007 ds and algorithm session_10
07 ds and algorithm session_10Niit Care
 
Babar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and RepresentationBabar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and RepresentationPierre de Lacaze
 
Class 9: Consistent Hashing
Class 9: Consistent HashingClass 9: Consistent Hashing
Class 9: Consistent HashingDavid Evans
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Skills Matter
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_ormKenan Sevindik
 

Was ist angesagt? (20)

4.2 bst
4.2 bst4.2 bst
4.2 bst
 
E2
E2E2
E2
 
Python bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of NairobiPython bootcamp - C4Dlab, University of Nairobi
Python bootcamp - C4Dlab, University of Nairobi
 
09 logic programming
09 logic programming09 logic programming
09 logic programming
 
DataCamp Cheat Sheets 4 Python Users (2020)
DataCamp Cheat Sheets 4 Python Users (2020)DataCamp Cheat Sheets 4 Python Users (2020)
DataCamp Cheat Sheets 4 Python Users (2020)
 
binary_search
binary_searchbinary_search
binary_search
 
Java script objects 1
Java script objects 1Java script objects 1
Java script objects 1
 
Banishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHPBanishing Loops with Functional Programming in PHP
Banishing Loops with Functional Programming in PHP
 
Prolog programming
Prolog programmingProlog programming
Prolog programming
 
08 ds and algorithm session_11
08 ds and algorithm session_1108 ds and algorithm session_11
08 ds and algorithm session_11
 
07 ds and algorithm session_10
07 ds and algorithm session_1007 ds and algorithm session_10
07 ds and algorithm session_10
 
Babar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and RepresentationBabar: Knowledge Recognition, Extraction and Representation
Babar: Knowledge Recognition, Extraction and Representation
 
Class 9: Consistent Hashing
Class 9: Consistent HashingClass 9: Consistent Hashing
Class 9: Consistent Hashing
 
binary_trees2
binary_trees2binary_trees2
binary_trees2
 
Ggplot2 v3
Ggplot2 v3Ggplot2 v3
Ggplot2 v3
 
ch5
ch5ch5
ch5
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
 
Prolog 7-Languages
Prolog 7-LanguagesProlog 7-Languages
Prolog 7-Languages
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
 

Ähnlich wie Tree & bst

Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdfssuser50179b
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structureShakil Ahmed
 
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 .pptxasimshahzad8611
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary treeZaid Shabbir
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.pptItsStranger1
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).pptplagcheck
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.pptplagcheck
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptDharmannaRathod1
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfssuser034ce1
 
1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdfarjuncp10
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docxajoy21
 

Ähnlich wie Tree & bst (20)

Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
Advanced data structure
Advanced data structureAdvanced data structure
Advanced data structure
 
Chap 5 Tree.ppt
Chap 5 Tree.pptChap 5 Tree.ppt
Chap 5 Tree.ppt
 
Unit8 C
Unit8 CUnit8 C
Unit8 C
 
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
 
Trees
TreesTrees
Trees
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
Unit 4 tree
Unit 4   treeUnit 4   tree
Unit 4 tree
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
BinarySearchTrees (1).ppt
BinarySearchTrees (1).pptBinarySearchTrees (1).ppt
BinarySearchTrees (1).ppt
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
BinarySearchTrees.ppt
BinarySearchTrees.pptBinarySearchTrees.ppt
BinarySearchTrees.ppt
 
data structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.pptdata structure very BinarySearchTrees.ppt
data structure very BinarySearchTrees.ppt
 
CS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdfCS-102 BST_27_3_14v2.pdf
CS-102 BST_27_3_14v2.pdf
 
1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf1. Add a breadth-first (level-order) traversal function to the binar.pdf
1. Add a breadth-first (level-order) traversal function to the binar.pdf
 
#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx#include iostream using namespace std; const int nil = 0; cl.docx
#include iostream using namespace std; const int nil = 0; cl.docx
 
Tree
TreeTree
Tree
 
Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 

Mehr von Shakil Ahmed (20)

Algorithm
AlgorithmAlgorithm
Algorithm
 
B-tree & R-tree
B-tree & R-treeB-tree & R-tree
B-tree & R-tree
 
Prototype pattern
Prototype patternPrototype pattern
Prototype pattern
 
Observer pattern
Observer patternObserver pattern
Observer pattern
 
Mediator pattern
Mediator patternMediator pattern
Mediator pattern
 
Flyweight pattern
Flyweight patternFlyweight pattern
Flyweight pattern
 
Facade pattern
Facade patternFacade pattern
Facade pattern
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Command pattern
Command patternCommand pattern
Command pattern
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Bridge pattern
Bridge patternBridge pattern
Bridge pattern
 
Adapter pattern
Adapter patternAdapter pattern
Adapter pattern
 
Proxy pattern
Proxy patternProxy pattern
Proxy pattern
 
iOS 5
iOS 5iOS 5
iOS 5
 
Ios development
Ios developmentIos development
Ios development
 
Graph
GraphGraph
Graph
 
Lowest common ancestor
Lowest common ancestorLowest common ancestor
Lowest common ancestor
 
Segment tree
Segment treeSegment tree
Segment tree
 
Trie tree
Trie treeTrie tree
Trie tree
 

Kürzlich hochgeladen

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 

Kürzlich hochgeladen (20)

PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 

Tree & bst

  • 1. Tree & BST Md. Shakil Ahmed Software Engineer Astha it research & consultancy ltd. Dhaka, Bangladesh
  • 4. Unix / Windows file structure
  • 5. Definition of Tree A tree is a finite set of one or more nodes such that: There is a specially designated node called the root. The remaining nodes are partitioned into n>=0 disjoint sets T1, ..., Tn, where each of these sets is a tree. We call T1, ..., Tn the subtrees of the root.
  • 6. Level and Depth Level node (13) degree of a node 1 leaf (terminal) 3 A 1 nonterminal 2 parent children 2 B 2 1 C 2 3 D 2 3 sibling degree of a tree (3) E 3 F 3 G 31 H I 3 J 4 2 0 0 30 0 3 ancestor level of a node height of a tree (4) 0 K 4 L 0 M 4 0 4
  • 7. Binary Tree • Each Node can have at most 2 children.
  • 8. Array Representation 1 • With in a single array. • If root position is i then, • Left Child in 2*i+1 • Right Child is 2*i+2 • For N level tree it needs 2^N – 1 memory space. • If current node is i then it’s parent is i/2. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 7 5 2 6 -1 9 -1 -1 5 11 -1 -1 4 -1
  • 9. Array Representation 1 • Advantage -> 1.Good in Full Or Complete Binary tree • Disadvantage 1.If we use it in normal binary tree then it may be huge memory lose.
  • 10. Array Representation 2 • Use 3 Parallel Array 0 1 2 3 4 5 6 7 8 Root 2 7 5 2 6 9 5 11 4 Left 1 3 -1 -1 6 8 -1 -1 -1 Right 2 4 5 -1 7 -1 -1 -1 -1 • If you need parent 0 1 2 3 4 5 6 7 8 Root 2 7 5 2 6 9 5 11 4 Left 1 3 -1 -1 6 8 -1 -1 -1 Right 2 4 5 -1 7 -1 -1 -1 -1 Parent -1 0 0 1 1 2 4 4 5
  • 11. Linked Representation typedef struct tnode *ptnode; typedef struct tnode { int data; ptnode left, right; }; data left data right left right
  • 12. Preorder Traversal (recursive version) Linked Representation Array Representation 2 void preorder(ptnode ptr) void preorder(int nodeIndex) /* preorder tree traversal */ { { printf(“%d”, root[nodeIndex]); if (ptr) { if(Left[nodeIndex]!=-1) printf(“%d”, ptr- preorder(Left[nodeIndex]); >data); if(Right[nodeIndex]!=-1) preorder(ptr->left); preorder(Right[nodeIndex]); preorder(ptr->right); } } }
  • 13. Inorder Traversal (recursive version) Linked Representation Array Representation 2 void inorder(ptnode ptr) void inorder(int nodeIndex) /* inorder tree traversal */ { { if(Left[nodeIndex]!=-1) if (ptr) { inorder(Left[nodeIndex]); inorder(ptr->left); printf(“%d”, root[nodeIndex]); printf(“%d”, ptr->data); if(Right[nodeIndex]!=-1) inorder(ptr->right); inorder(Right[nodeIndex]); } } }
  • 14. Postorder Traversal (recursive version) Linked Representation Array Representation 2 void postorder(ptnode ptr) void postorder(int nodeIndex) /* postorder tree traversal */ { { if(Left[nodeIndex]!=-1) if (ptr) { postorder(Left[nodeIndex]); postorder(ptr->left); if(Right[nodeIndex]!=-1) postorder(ptr->right); postorder(Right[nodeIndex]); printf(“%d”, ptr->data); printf(“%d”, root[nodeIndex]); } } }
  • 15. Binary Search Tree • All items in the left subtree are less than the root. • All items in the right subtree are greater or equal to the root. • Each subtree is itself a binary search tree.
  • 17. Binary Search Tree Elements => 23 18 12 20 44 52 35 1st Element 2nd Element 3rd Element
  • 18. Binary Search Tree 4th Element 5th Element
  • 19. Binary Search Tree 6th Element 7th Element
  • 21. Binary Search Tree //Array Representation 2 root = 0; //Generate BST while(1){ int N = 0; if(Root[root]==value) int Root[1000000], break; Left[1000000], else if(Root[root]>value) Right[1000000]; { if(Left[root]!=-1) void AddToBST(int value) root = Left[root]; { else if(N==0) { { Root[N]=value; Root[N]=value; Left[N]=-1; Left[N]=-1; Right[N]=-1; Right[N]=-1; Left[root]=N; } N++; else break; { } }
  • 22. Binary Search Tree else Client Code => { scanf(“%d”,&n); if(Right[root]!=-1) root = Right[root]; for(i=0;i<n;i++) else { { scanf(“%d”,&t); Root[N]=value; AddToBST(t); Left[N]=-1; } Right[N]=-1; Right[root]=N; N++; break; } } } } }
  • 23. Binary Search Tree //Array Representation 2 else //Search in BST { int SearchInBST(int value) if(Right[root]!=-1) { root = Right[root]; if(N==0) else return -1; return -1; } root = 0; } while(1) return -1; { } if(Root[root]==value) return root; Client Code => else if(Root[root]>value) scanf(“%d”,&n); { for(i=0;i<n;i++) if(Left[root]!=-1) { root = Left[root]; scanf(“%d”,&t); else Printf(“%d”,SearchInBST(t)); return -1; } }
  • 24. Sample LightOj => • http://www.lightoj.com/volume_showproble m.php?problem=1087 • http://www.lightoj.com/volume_showproble m.php?problem=1097 • http://www.lightoj.com/volume_showproble m.php?problem=1293