SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Threaded Binary Tree.pptx
Threaded Binary Tree.pptxThreaded Binary Tree.pptx
Threaded Binary Tree.pptx
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Threaded Binary Tree
Threaded Binary TreeThreaded Binary Tree
Threaded Binary Tree
 
linked lists in data structures
linked lists in data structureslinked lists in data structures
linked lists in data structures
 
Stack
StackStack
Stack
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Data Structure (Tree)
Data Structure (Tree)Data Structure (Tree)
Data Structure (Tree)
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 
BINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.pptBINARY TREE REPRESENTATION.ppt
BINARY TREE REPRESENTATION.ppt
 
B trees in Data Structure
B trees in Data StructureB trees in Data Structure
B trees in Data Structure
 
Adjacency list
Adjacency listAdjacency list
Adjacency list
 
Linked list
Linked listLinked list
Linked list
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Red black tree
Red black treeRed black tree
Red black tree
 
Heap tree
Heap treeHeap tree
Heap tree
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Data structure - Graph
Data structure - GraphData structure - Graph
Data structure - Graph
 

Destacado (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 a 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
 
trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
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 a Binary tree (20)

Tree
TreeTree
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
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
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
 

Más de 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
 

Último

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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