SlideShare a Scribd company logo
1 of 34
Download to read offline
Trees


Non-Linear Data Structure
Non-Linear Data Structure
• These data structures donot have their
  elements in a sequence.
• Trees is an example.
• Trees are mainly used to represent data
  containing a hierarchical relationship
  between elements, ex : records, family
  trees and table of contents.
Terminology of Trees
• The boxes on the tree are called nodes
• The nodes immediately below (to the left and right of) a given node
  are called its children
• The node immediately above a given node is called its parent
• The (unique) node without a parent is called the root
• A node with no children is called a leaf
• Two children of the same parent are said to be siblings
• A node can be an ancestor (e.g. grandparent) or a descendant
  (e.g. great-grandchild)
Some tree terminology
• root: node with no parent
   – A non-empty tree has exactly one root

• leaf: node with no children

• siblings: two nodes with the same parent.

• path: a sequence of nodes n1, n2, … , nk such that ni is the parent of
  ni+1 for 1 ≤ i < k
    – in other words, a sequence of hops to get from one node to
      another
    – the length of a path is the number of edges in the path, or 1 less
      than the number of nodes in it
Depth and height
• depth or level: length of the path from root to the current node
      (depth of root = 0)

• height: length of the longest path from root to any leaf
   – empty (null) tree's height: -1
   – single-element tree's height: 0
   – tree with a root with children: 1
Tree example
Trees
• Tree nodes contain two or more links
  – All other data structures we have discussed
   only contain one
• Binary trees
  – All nodes contain two links
     • None, one, or both of which may be NULL
  – The root node is the first node in a tree.
  – Each link in the root node refers to a child
  – A node with no children is called a leaf node
Binary Trees
• Special type of tree in which every node or
  vertex has either no children, one child or
  two children.
• Characteristics :
  • Every binary tree has a root pointer which
    points to the start of the tree.
  • A binary tree can be empty.
  • It consists of a node called root, a left subtree
    and right subtree both of which are binary
    trees themselves.
Examples : Binary Trees
    (1)            (2)              (3)                         (4)

    X                 X               X                          X



               Y                              Z         Y             Z
Root of tree is node having info as X.
(1) Only node is root.
(2) Root has left child Y.                                       A
(3) Root X has right child Z.
(4) Root X has left child Y and right child Z which
    is again a binary tree with its parent as Z and         B             C
    left child of Z is A, which in turn is parent for
    left child B and right child C.
Properties of Binary Tree
• A tree with n nodes has exactly (n-1) edges or
  branches.
• In a tree every node except the root has exactly
  one parent (and the root node does not have a
  parent).
• There is exactly one path connecting any two
  nodes in a tree.
• The maximum number of nodes in a binary tree
  of height K is 2K+1 -1 where K>=0.
Representation of Binary Tree
• Array representation                            X

     – The root of the tree is
       stored in position 0.
                                          Y            Z
     – The node in position p, is
       the implicit father of nodes
       2p+1 and 2p+2.                             A
     – Left child is at 2p+1 and
       right at 2p+2.
                                              B            C
 0    1    2   3   4     5   6    7   8       9   10       11   12
X     Y   Z             A                                  B    C
Representation of Binary Tree
• Linked List
  • Every node will consists of information, and two
    pointers left and right pointing to the left and right
    child nodes.
     struct node
     {
          int data;
          struct node *left;
          struct node *right;
     };
  • The topmost node or first node is pointed by a root
    pointer which will inform the start of the tree. Rest of
    the nodes are attached either to left if less than parent
    or right if more or equal to parent.
• Diagram of a binary tree


                    B


               A            D


                        C
Operations on Binary Tree
•   Searching an existing node.
•   Inserting a new node.
•   Deleting an existing node.
•   Traversing the tree.
    • Preorder
    • Inorder
    • Postorder
Search Process
• Initialize a search pointer as the root pointer.
• All the data is compared with the data stored in each
  node of the tree starting from root node.
• If the data to be searched is equal to the data of the
  node then print “successful” search.
• Else if the data is less than node’s data move the pointer
  to left subtree. Else data is more than node’s data move
  the pointer to right subtree.
• Keep moving in the tree until the data is found or search
  pointer comes to NULL in which case it is an
  “unsuccessful” search.
Example used for Search
                 21         Root


            18


        7         19


    6       9


        8        11

                       14


                  13
Example : Search
• Initialize temp as root pointer which is node having 21.
• Loop until temp!=NULL or ITEM found
   • Compare item=9 with the root 21 of the tree, since
      9<21, proceed temp to the left child of the tree.
   • Compare ITEM=9 with 18 since 9<18 proceed temp
      to the left subtree of 18, which is 7.
   • Compare ITEM=9 with 7 since 9>7 proceed temp to
      right subtree of the node which holds a value 7.
   • Now ITEM=9 is compared with the node which holds
      value 9 and since 9 is found the searching process
      ens here.
Insert Process
• For node insertion in a binary search tree, initially the
  data that is to be inserted is compared with the data of
  the root data.
• If the data is found to be greater than or equal to the
  data of the root node then the new node is inserted in
  the right subtree of the root node, else left subtree.
• Now the parent of the right or left subtree is considered
  and its data is compared with the data of the new node
  and the same procedure is repeated again until a NULL
  is found which will indicate a space when the new node
  has to be attached. Thus finally the new node is made
  the appropriate child of this current node.
Example used for Insert
                 38        Root



      14                    56


            23        45              82
  8



       18                        70



            20
Example : Insert
• Suppose the ITEM=20 is the data part of the new node
  to be inserted in the tree and the root is pointing to the
  start of the tree.
• Compare ITEM=20 with the root 38 of the tree. Since 20
  < 38 proceed to the left child of 38, which is 14.
• Compare ITEM=20 with 14, since 20 > 14 proceed to the
  right child of 14, which is 23.
• Compare ITEM=20 with 23 since 20 < 23 proceed to the
  left child of 23 which is 18.
• Compare ITEM=20 with 18 since 20 > 18 and 18 does
  not have right child, 10 is inserted as the right child of 18.
• Tree traversals:
  – Inorder traversal – prints the node values in ascending order
      1. Traverse the left subtree with an inorder traversal
      2. Process the value in the node (i.e., print the node value)
      3. Traverse the right subtree with an inorder traversal
  – Preorder traversal
      1. Process the value in the node
      2. Traverse the left subtree with a preorder traversal
      3. Traverse the right subtree with a preorder traversal
  – Postorder traversal
      1. Traverse the left subtree with a postorder traversal
      2. Traverse the right subtree with a postorder traversal
      3. Process the value in the node
Binary tree traversals
• three common binary tree traversal orderings
  (each one begins at the root):

   – preorder traversal: the current node is processed, then the
     node's left subtree is traversed, then the node's right subtree is
     traversed (CURRENT-LEFT-RIGHT)

   – in-order traversal: the node's left subtree is traversed, then the
     current node itself is processed, then the node's right subtree is
     traversed (LEFT-CURRENT-RIGHT)

   – postorder traversal: the node's left subtree is traversed, then
     the node's right subtree is traversed, and lastly the current node
     is processed (LEFT-RIGHT-CURRENT)
Binary tree preorder traversal
• order: C F T B R K G
   – The trick: Walk around the outside of the tree and emit a node's
     value when you touch the left side of the node.

                            root
                                         "C"


                                   "F"              "G"

                      "T"                  "K"

            "B"                    "R"
Binary tree in-order traversal
• order: B T R F K C G
   – The trick: Walk around the outside of the tree and emit a node's
     value when you touch the bottom side of the node.

                           root
                                         "C"


                                  "F"               "G"

                     "T"                   "K"


            "B"                   "R"
Binary tree postorder traversal
• order: B R T K F G C
   – The trick: Walk around the outside of the tree and emit a node's
     value when you touch the right side of the node

                           root
                                        "C"


                                  "F"              "G"

                     "T"                   "K"

           "B"                    "R"
Delete Process
•   There are four possible conditions are to be taken into account :
      i. No node in the tree holds the specified data.
      ii. The node containing the data has no children.
      iii. The node containing the data has exactly one child.
      iv. The node containing data has two children.
•   Condition (i) In this case we simply print the message that the data
    item is not present in the tree.
•   Condition (ii) In this case since the node to be deleted has no
    children the memory occupied by this should be freed and either
    the left link or the right link of the parent of this node should be set
    to NULL. Which of these is to be set to NULL depends upon
    whether the node being deleted is a left child or right child of its
    parent.
Condition (iii)
    •   In this case since the node to be deleted has one child the solution is to
        adjust the pointer of the parent of the node to be deleted such that after
        deletion it points to the child of the node being deleted as in the diagram.
                                   Root                                         Root
                       21                                        21


              18            24                             18          24


        7             19         26                  7          19            26


6            9              25        30        6          11           25         30


                       11                             10

                 10
Condition (iv)
    In this case the node to be deleted has two children. Consider node 9 before deletion. The inorder successor of the
    node 9 is node 10. The data of this inorder successor should now be copied into the node to be deleted and a pointer
    should be set up pointing to the inorder successor (node 10). This inorder successor would always have one or zero
    child. It should then be deleted using the same procedure as for deleting one child or a zero child node. Thus, the whole
    logic of deleting a node with two children is to locate the inorder successor, copy its data and reduce the problem to a
    simple deletion of a node with one or zero child. This is shown in the example.

                                                 Root                                                                Root
                          21                                                                  21


                 18                 24                                               18                24


        7                19                   26                            7              19                    26


6               9                    25              30             6               10                  25              30


        8                 11                                                8                11


                    10        Inorder successor of node 9
Deletion
• Condition (i) Print message data not found.
• Condition (ii) Since no children so free the node
  & make either parent->left=NULL or parent-
  >right=NULL.

              Parent        A      A      Parent

                 left                          right

                X      B                   C           X
  In the example1,                     In the example2,
  parent->left==x so free(x) and       parent->right==x so free(x) and
  make parent->left=NULL.              make parent->right=NULL.
Deletion
•         Condition (iii) Adjust parent to point to the child of the deleted node.
I.        Node deleted(X) has only left child :
     1)      If(parent->left==x) parent->left=x->left.
     2)      If(parent->right==x) parent->right=x->left.



             Parent            A                           A   Parent

                    left                                           right

              X            B                                   B           X

             left
                                                                 right
                C                                          C
Deletion
•          Condition (iii) Adjust parent to point to the child of the deleted node.
II.        Node deleted(X) has only right child :
      1)      If(parent->left==x) parent->left=x->right.
      2)      If(parent->right==x) parent->right=x->right.



              Parent              A                          A   Parent

                   left                                              right

               X          B                                      B           X
                                                                          right
                          right
                                  C                                          C
Deletion
•   Condition (iv) solution more complex as X has two children,
•   Find inorder successor of the node X. Inorder successor of any node will be first go to right of the
    node and then from that node keep going left until NULL encountered, that will be the inorder
    successor.
•   Copy data of inorder successor to node X’s data.
•   Place pointer at the inorder successor node. Now the inorder succesor will have zero or one child
    only (so the complex problem is reduced to condition (iii)).
•   Delete the inorder successor node by using logic of condition (ii) if no children or condition (iiii) if one
    right child.

          Parent             A                                               Parent             A
                    left                                                               left
           X         B                                                                  E
                                                                              X
           left              right                                            left              right
             C               D                                                  C               D
                      left                                                               left
                                        Here inorder successor E has
                       E                no children condition (ii)                        E
Deletion
Parent            A                Parent            A                Parent                A

         left                               left                                left

X         B                                  E                                   E
left              right             left             right             left                 right

  C               D                  C               D                  C                   D
           left                               left
                                                                                     left
            E          Inorder      X          E          Inorder
                       Successor                          Successor                     F
          right                              right                            left              right
                   F                                  F
                                                                               G                H
           left           right               left           right
                                                                       Here inorder successor E has
            G             H                    G             H         one right child condition (iii)
                                                                       If(parent->left==x)
                                                                       parent->left=x->right.
Application of Tree
• Expression Tree
• Game Tree

More Related Content

What's hot (20)

Trees data structure
Trees data structureTrees data structure
Trees data structure
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Array data structure
Array data structureArray data structure
Array data structure
 
B+ trees and height balance tree
B+ trees and height balance treeB+ trees and height balance tree
B+ trees and height balance tree
 
Trees
TreesTrees
Trees
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
Binary search tree in data structures
Binary search tree in  data structuresBinary search tree in  data structures
Binary search tree in data structures
 
Infix to postfix conversion
Infix to postfix conversionInfix to postfix conversion
Infix to postfix conversion
 
Linked list
Linked listLinked list
Linked list
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
Trees
Trees Trees
Trees
 
Expression trees
Expression treesExpression trees
Expression trees
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Red black tree
Red black treeRed black tree
Red black tree
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Binary search tree operations
Binary search tree operationsBinary search tree operations
Binary search tree operations
 

Viewers also liked

Viewers also liked (8)

Computer arithmetic
Computer arithmeticComputer arithmetic
Computer arithmetic
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
3D X Point Innovation by Intel Corporation inc
3D X Point Innovation by Intel Corporation inc3D X Point Innovation by Intel Corporation inc
3D X Point Innovation by Intel Corporation inc
 
Lecture 16
Lecture 16Lecture 16
Lecture 16
 
Intel Core i7 Processors
Intel Core i7 ProcessorsIntel Core i7 Processors
Intel Core i7 Processors
 
Lecture 47
Lecture 47Lecture 47
Lecture 47
 
Computer arithmetic
Computer arithmeticComputer arithmetic
Computer arithmetic
 
Arrays
ArraysArrays
Arrays
 

Similar to Binary tree

tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptxMouDhara1
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAdityaK92
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basicsVivek Bhargav
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree dsViji B
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap treezia eagle
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10sumitbardhan
 
Data structure(Part 2)
Data structure(Part 2)Data structure(Part 2)
Data structure(Part 2)SURBHI SAROHA
 
Tree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data StructureTree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data StructureManoj PAtil
 

Similar to Binary tree (20)

Tree
TreeTree
Tree
 
Binary tree
Binary tree Binary tree
Binary tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
tree-160731205832.pptx
tree-160731205832.pptxtree-160731205832.pptx
tree-160731205832.pptx
 
Tree.pptx
Tree.pptxTree.pptx
Tree.pptx
 
TREES34.pptx
TREES34.pptxTREES34.pptx
TREES34.pptx
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Tree
TreeTree
Tree
 
Data structures 3
Data structures 3Data structures 3
Data structures 3
 
Tree
TreeTree
Tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Unit 3 trees
Unit 3   treesUnit 3   trees
Unit 3 trees
 
Lecture 9: Binary tree basics
Lecture 9: Binary tree basicsLecture 9: Binary tree basics
Lecture 9: Binary tree basics
 
DSA-Unit-2.pptx
DSA-Unit-2.pptxDSA-Unit-2.pptx
DSA-Unit-2.pptx
 
Introduction to tree ds
Introduction to tree dsIntroduction to tree ds
Introduction to tree ds
 
Search tree,Tree and binary tree and heap tree
Search tree,Tree  and binary tree and heap treeSearch tree,Tree  and binary tree and heap tree
Search tree,Tree and binary tree and heap tree
 
358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10358 33 powerpoint-slides_10-trees_chapter-10
358 33 powerpoint-slides_10-trees_chapter-10
 
Data structure(Part 2)
Data structure(Part 2)Data structure(Part 2)
Data structure(Part 2)
 
Tree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data StructureTree Basic concepts of Tree in Data Structure
Tree Basic concepts of Tree in Data Structure
 

More from Ssankett Negi (10)

Multi way&btree
Multi way&btreeMulti way&btree
Multi way&btree
 
Heapsort
HeapsortHeapsort
Heapsort
 
Binary trees
Binary treesBinary trees
Binary trees
 
Threaded binarytree&heapsort
Threaded binarytree&heapsortThreaded binarytree&heapsort
Threaded binarytree&heapsort
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Stack prgs
Stack prgsStack prgs
Stack prgs
 
Recursion
RecursionRecursion
Recursion
 
Qprgs
QprgsQprgs
Qprgs
 
Circular queues
Circular queuesCircular queues
Circular queues
 
U2.linked list
U2.linked listU2.linked list
U2.linked list
 

Recently uploaded

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 

Binary tree

  • 2. Non-Linear Data Structure • These data structures donot have their elements in a sequence. • Trees is an example. • Trees are mainly used to represent data containing a hierarchical relationship between elements, ex : records, family trees and table of contents.
  • 3. Terminology of Trees • The boxes on the tree are called nodes • The nodes immediately below (to the left and right of) a given node are called its children • The node immediately above a given node is called its parent • The (unique) node without a parent is called the root • A node with no children is called a leaf • Two children of the same parent are said to be siblings • A node can be an ancestor (e.g. grandparent) or a descendant (e.g. great-grandchild)
  • 4. Some tree terminology • root: node with no parent – A non-empty tree has exactly one root • leaf: node with no children • siblings: two nodes with the same parent. • path: a sequence of nodes n1, n2, … , nk such that ni is the parent of ni+1 for 1 ≤ i < k – in other words, a sequence of hops to get from one node to another – the length of a path is the number of edges in the path, or 1 less than the number of nodes in it
  • 5. Depth and height • depth or level: length of the path from root to the current node (depth of root = 0) • height: length of the longest path from root to any leaf – empty (null) tree's height: -1 – single-element tree's height: 0 – tree with a root with children: 1
  • 7. Trees • Tree nodes contain two or more links – All other data structures we have discussed only contain one • Binary trees – All nodes contain two links • None, one, or both of which may be NULL – The root node is the first node in a tree. – Each link in the root node refers to a child – A node with no children is called a leaf node
  • 8. Binary Trees • Special type of tree in which every node or vertex has either no children, one child or two children. • Characteristics : • Every binary tree has a root pointer which points to the start of the tree. • A binary tree can be empty. • It consists of a node called root, a left subtree and right subtree both of which are binary trees themselves.
  • 9. Examples : Binary Trees (1) (2) (3) (4) X X X X Y Z Y Z Root of tree is node having info as X. (1) Only node is root. (2) Root has left child Y. A (3) Root X has right child Z. (4) Root X has left child Y and right child Z which is again a binary tree with its parent as Z and B C left child of Z is A, which in turn is parent for left child B and right child C.
  • 10. Properties of Binary Tree • A tree with n nodes has exactly (n-1) edges or branches. • In a tree every node except the root has exactly one parent (and the root node does not have a parent). • There is exactly one path connecting any two nodes in a tree. • The maximum number of nodes in a binary tree of height K is 2K+1 -1 where K>=0.
  • 11. Representation of Binary Tree • Array representation X – The root of the tree is stored in position 0. Y Z – The node in position p, is the implicit father of nodes 2p+1 and 2p+2. A – Left child is at 2p+1 and right at 2p+2. B C 0 1 2 3 4 5 6 7 8 9 10 11 12 X Y Z A B C
  • 12. Representation of Binary Tree • Linked List • Every node will consists of information, and two pointers left and right pointing to the left and right child nodes. struct node { int data; struct node *left; struct node *right; }; • The topmost node or first node is pointed by a root pointer which will inform the start of the tree. Rest of the nodes are attached either to left if less than parent or right if more or equal to parent.
  • 13. • Diagram of a binary tree B A D C
  • 14. Operations on Binary Tree • Searching an existing node. • Inserting a new node. • Deleting an existing node. • Traversing the tree. • Preorder • Inorder • Postorder
  • 15. Search Process • Initialize a search pointer as the root pointer. • All the data is compared with the data stored in each node of the tree starting from root node. • If the data to be searched is equal to the data of the node then print “successful” search. • Else if the data is less than node’s data move the pointer to left subtree. Else data is more than node’s data move the pointer to right subtree. • Keep moving in the tree until the data is found or search pointer comes to NULL in which case it is an “unsuccessful” search.
  • 16. Example used for Search 21 Root 18 7 19 6 9 8 11 14 13
  • 17. Example : Search • Initialize temp as root pointer which is node having 21. • Loop until temp!=NULL or ITEM found • Compare item=9 with the root 21 of the tree, since 9<21, proceed temp to the left child of the tree. • Compare ITEM=9 with 18 since 9<18 proceed temp to the left subtree of 18, which is 7. • Compare ITEM=9 with 7 since 9>7 proceed temp to right subtree of the node which holds a value 7. • Now ITEM=9 is compared with the node which holds value 9 and since 9 is found the searching process ens here.
  • 18. Insert Process • For node insertion in a binary search tree, initially the data that is to be inserted is compared with the data of the root data. • If the data is found to be greater than or equal to the data of the root node then the new node is inserted in the right subtree of the root node, else left subtree. • Now the parent of the right or left subtree is considered and its data is compared with the data of the new node and the same procedure is repeated again until a NULL is found which will indicate a space when the new node has to be attached. Thus finally the new node is made the appropriate child of this current node.
  • 19. Example used for Insert 38 Root 14 56 23 45 82 8 18 70 20
  • 20. Example : Insert • Suppose the ITEM=20 is the data part of the new node to be inserted in the tree and the root is pointing to the start of the tree. • Compare ITEM=20 with the root 38 of the tree. Since 20 < 38 proceed to the left child of 38, which is 14. • Compare ITEM=20 with 14, since 20 > 14 proceed to the right child of 14, which is 23. • Compare ITEM=20 with 23 since 20 < 23 proceed to the left child of 23 which is 18. • Compare ITEM=20 with 18 since 20 > 18 and 18 does not have right child, 10 is inserted as the right child of 18.
  • 21. • Tree traversals: – Inorder traversal – prints the node values in ascending order 1. Traverse the left subtree with an inorder traversal 2. Process the value in the node (i.e., print the node value) 3. Traverse the right subtree with an inorder traversal – Preorder traversal 1. Process the value in the node 2. Traverse the left subtree with a preorder traversal 3. Traverse the right subtree with a preorder traversal – Postorder traversal 1. Traverse the left subtree with a postorder traversal 2. Traverse the right subtree with a postorder traversal 3. Process the value in the node
  • 22. Binary tree traversals • three common binary tree traversal orderings (each one begins at the root): – preorder traversal: the current node is processed, then the node's left subtree is traversed, then the node's right subtree is traversed (CURRENT-LEFT-RIGHT) – in-order traversal: the node's left subtree is traversed, then the current node itself is processed, then the node's right subtree is traversed (LEFT-CURRENT-RIGHT) – postorder traversal: the node's left subtree is traversed, then the node's right subtree is traversed, and lastly the current node is processed (LEFT-RIGHT-CURRENT)
  • 23. Binary tree preorder traversal • order: C F T B R K G – The trick: Walk around the outside of the tree and emit a node's value when you touch the left side of the node. root "C" "F" "G" "T" "K" "B" "R"
  • 24. Binary tree in-order traversal • order: B T R F K C G – The trick: Walk around the outside of the tree and emit a node's value when you touch the bottom side of the node. root "C" "F" "G" "T" "K" "B" "R"
  • 25. Binary tree postorder traversal • order: B R T K F G C – The trick: Walk around the outside of the tree and emit a node's value when you touch the right side of the node root "C" "F" "G" "T" "K" "B" "R"
  • 26. Delete Process • There are four possible conditions are to be taken into account : i. No node in the tree holds the specified data. ii. The node containing the data has no children. iii. The node containing the data has exactly one child. iv. The node containing data has two children. • Condition (i) In this case we simply print the message that the data item is not present in the tree. • Condition (ii) In this case since the node to be deleted has no children the memory occupied by this should be freed and either the left link or the right link of the parent of this node should be set to NULL. Which of these is to be set to NULL depends upon whether the node being deleted is a left child or right child of its parent.
  • 27. Condition (iii) • In this case since the node to be deleted has one child the solution is to adjust the pointer of the parent of the node to be deleted such that after deletion it points to the child of the node being deleted as in the diagram. Root Root 21 21 18 24 18 24 7 19 26 7 19 26 6 9 25 30 6 11 25 30 11 10 10
  • 28. Condition (iv) In this case the node to be deleted has two children. Consider node 9 before deletion. The inorder successor of the node 9 is node 10. The data of this inorder successor should now be copied into the node to be deleted and a pointer should be set up pointing to the inorder successor (node 10). This inorder successor would always have one or zero child. It should then be deleted using the same procedure as for deleting one child or a zero child node. Thus, the whole logic of deleting a node with two children is to locate the inorder successor, copy its data and reduce the problem to a simple deletion of a node with one or zero child. This is shown in the example. Root Root 21 21 18 24 18 24 7 19 26 7 19 26 6 9 25 30 6 10 25 30 8 11 8 11 10 Inorder successor of node 9
  • 29. Deletion • Condition (i) Print message data not found. • Condition (ii) Since no children so free the node & make either parent->left=NULL or parent- >right=NULL. Parent A A Parent left right X B C X In the example1, In the example2, parent->left==x so free(x) and parent->right==x so free(x) and make parent->left=NULL. make parent->right=NULL.
  • 30. Deletion • Condition (iii) Adjust parent to point to the child of the deleted node. I. Node deleted(X) has only left child : 1) If(parent->left==x) parent->left=x->left. 2) If(parent->right==x) parent->right=x->left. Parent A A Parent left right X B B X left right C C
  • 31. Deletion • Condition (iii) Adjust parent to point to the child of the deleted node. II. Node deleted(X) has only right child : 1) If(parent->left==x) parent->left=x->right. 2) If(parent->right==x) parent->right=x->right. Parent A A Parent left right X B B X right right C C
  • 32. Deletion • Condition (iv) solution more complex as X has two children, • Find inorder successor of the node X. Inorder successor of any node will be first go to right of the node and then from that node keep going left until NULL encountered, that will be the inorder successor. • Copy data of inorder successor to node X’s data. • Place pointer at the inorder successor node. Now the inorder succesor will have zero or one child only (so the complex problem is reduced to condition (iii)). • Delete the inorder successor node by using logic of condition (ii) if no children or condition (iiii) if one right child. Parent A Parent A left left X B E X left right left right C D C D left left Here inorder successor E has E no children condition (ii) E
  • 33. Deletion Parent A Parent A Parent A left left left X B E E left right left right left right C D C D C D left left left E Inorder X E Inorder Successor Successor F right right left right F F G H left right left right Here inorder successor E has G H G H one right child condition (iii) If(parent->left==x) parent->left=x->right.
  • 34. Application of Tree • Expression Tree • Game Tree