SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Binary Trees
Parts of a binary tree
   A binary tree is composed of zero or more nodes
   Each node contains:
       A value (some sort of data item)
       A reference or pointer to a left child (may be null), and
       A reference or pointer to a right child (may be null)
   A binary tree may be empty (contain no nodes)
   If not empty, a binary tree has a root node
       Every node in the binary tree is reachable from the root
        node by a unique path
   A node with neither a left child nor a right child is
    called a leaf
       In some binary trees, only the leaves contain a value
                                                                    2
Picture of a binary tree

                       a


          b                    c



      d        e                       f


g          h       i               j       k


               l
                                               3
Size and depth
                                       The size of a binary tree is the
            a                           number of nodes in it
                                           This tree has size 12
        b           c                  The depth of a node is its
                                        distance from the root
    d       e               f
                                        
                                            a is at depth zero
                                        
                                            e is at depth 2
g       h       i       j       k
                                       The depth of a binary tree is
            l                           the depth of its deepest node
                                           This tree has depth 4


                                                                           4
Balance
                 a                                 a
         b               c                     b
                                           c       e
     d       e       f       g
                                       d       f
  h i              j
                                           g       h
A balanced binary tree
                                        i j
                                   An unbalanced binary tree
   A binary tree is balanced if every level above the lowest is “full”
    (contains 2n nodes)
   In most applications, a reasonably balanced binary tree is
    desirable
                                                                          5
Binary search in an array
   Look at array location (lo + hi)/2

           Searching for 5:
           (0+6)/2 = 3
                                          Using a binary
    hi = 2;
    (0 + 2)/2 = 1         lo = 2;         search tree
                          (2+2)/2=2
                                                      7

                                              3            13
       0     1   2    3       4   5   6
      2     3    5    7 11 13 17          2       5       11 17

                                                                  6
Tree traversals
   A binary tree is defined recursively: it consists of a root, a
    left subtree, and a right subtree
   To traverse (or walk) the binary tree is to visit each node in
    the binary tree exactly once
   Tree traversals are naturally recursive
   Since a binary tree has three “parts,” there are six possible
    ways to traverse the binary tree:
                                root, right, left
      root, left, right
                                right, root, left
      left, root, right
                                right, left, root
      left, right, root




                                                                     7
Preorder traversal
   In preorder, the root is visited first
   Here’s a preorder traversal to print out all the
    elements in the binary tree:

    public void preorderPrint(BinaryTree bt) {
       if (bt == null) return;
       System.out.println(bt.value);
       preorderPrint(bt.leftChild);
       preorderPrint(bt.rightChild);
    }



                                                       8
Inorder traversal
   In inorder, the root is visited in the middle
   Here’s an inorder traversal to print out all the
    elements in the binary tree:

    public void inorderPrint(BinaryTree bt) {
       if (bt == null) return;
       inorderPrint(bt.leftChild);
       System.out.println(bt.value);
       inorderPrint(bt.rightChild);
    }



                                                       9
Postorder traversal
   In postorder, the root is visited last
   Here’s a postorder traversal to print out all the
    elements in the binary tree:

    public void postorderPrint(BinaryTree bt) {
       if (bt == null) return;
       postorderPrint(bt.leftChild);
       postorderPrint(bt.rightChild);
       System.out.println(bt.value);
    }



                                                        10
Tree traversals using “flags”
   The order in which the nodes are visited during a tree
    traversal can be easily determined by imagining there is a
    “flag” attached to each node, as follows:



             preorder                    inorder                     postorder

   To traverse the tree, collect the flags:
                 A                           A                           A

         B               C           B               C           B               C

     D       E       F       G   D       E       F       G   D       E       F       G

         ABDECFG                     DBEAFCG                     DEBFGCA
                                                                                         11
Copying a binary tree
   In postorder, the root is visited last
   Here’s a postorder traversal to make a complete
    copy of a given binary tree:

    public BinaryTree copyTree(BinaryTree bt) {
       if (bt == null) return null;
       BinaryTree left = copyTree(bt.leftChild);
       BinaryTree right = copyTree(bt.rightChild);
       return new BinaryTree(bt.value, left, right);
    }



                                                       12
Other traversals
   The other traversals are the reverse of these three
    standard ones
       That is, the right subtree is traversed before the left subtree
        is traversed
   Reverse preorder: root, right subtree, left subtree
   Reverse inorder: right subtree, root, left subtree
   Reverse postorder: right subtree, left subtree, root




                                                                          13
The End




          14

Weitere ähnliche Inhalte

Was ist angesagt?

non linear data structure -introduction of tree
non linear data structure -introduction of treenon linear data structure -introduction of tree
non linear data structure -introduction of tree
Siddhi Viradiya
 

Was ist angesagt? (20)

Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 
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
 
Trees
TreesTrees
Trees
 
Tree-In Data Structure
Tree-In Data StructureTree-In Data Structure
Tree-In Data Structure
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
non linear data structure -introduction of tree
non linear data structure -introduction of treenon linear data structure -introduction of tree
non linear data structure -introduction of tree
 
Chap 7 binary threaded tree
Chap 7 binary threaded treeChap 7 binary threaded tree
Chap 7 binary threaded tree
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
binary search tree
binary search treebinary search tree
binary search tree
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 

Andere mochten auch

14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
Tech_MX
 
Constants
ConstantsConstants
Constants
Tech_MX
 
Trends and technologies in system softwares
Trends and technologies in system softwaresTrends and technologies in system softwares
Trends and technologies in system softwares
Tech_MX
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classes
Tech_MX
 
Graph theory
Graph theoryGraph theory
Graph theory
Tech_MX
 
More on Lex
More on LexMore on Lex
More on Lex
Tech_MX
 
What are interpersonal skills
What are interpersonal skillsWhat are interpersonal skills
What are interpersonal skills
Tech_MX
 
Linear programming problem
Linear programming problemLinear programming problem
Linear programming problem
Tech_MX
 
Investment problem
Investment problemInvestment problem
Investment problem
Tech_MX
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
Tech_MX
 
Buddy system final
Buddy system finalBuddy system final
Buddy system final
Tech_MX
 
Set data structure
Set data structure Set data structure
Set data structure
Tech_MX
 
Graph data structure
Graph data structureGraph data structure
Graph data structure
Tech_MX
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
E post office system
E post office systemE post office system
E post office system
Tech_MX
 
Combined paging and segmentation
Combined paging and segmentationCombined paging and segmentation
Combined paging and segmentation
Tech_MX
 

Andere mochten auch (19)

14.jun.2012
14.jun.201214.jun.2012
14.jun.2012
 
Constants
ConstantsConstants
Constants
 
Trends and technologies in system softwares
Trends and technologies in system softwaresTrends and technologies in system softwares
Trends and technologies in system softwares
 
Mutable and immutable classes
Mutable and  immutable classesMutable and  immutable classes
Mutable and immutable classes
 
Graph theory
Graph theoryGraph theory
Graph theory
 
More on Lex
More on LexMore on Lex
More on Lex
 
What are interpersonal skills
What are interpersonal skillsWhat are interpersonal skills
What are interpersonal skills
 
Linear programming problem
Linear programming problemLinear programming problem
Linear programming problem
 
Investment problem
Investment problemInvestment problem
Investment problem
 
Set data structure 2
Set data structure 2Set data structure 2
Set data structure 2
 
Buddy system final
Buddy system finalBuddy system final
Buddy system final
 
Set data structure
Set data structure Set data structure
Set data structure
 
Graph data structure
Graph data structureGraph data structure
Graph data structure
 
Inline function
Inline functionInline function
Inline function
 
E post office system
E post office systemE post office system
E post office system
 
Combined paging and segmentation
Combined paging and segmentationCombined paging and segmentation
Combined paging and segmentation
 
Linkers
LinkersLinkers
Linkers
 
Uid
UidUid
Uid
 
Spss
SpssSpss
Spss
 

Ähnlich wie 09 binary-trees

Ähnlich wie 09 binary-trees (20)

Binary trees
Binary treesBinary trees
Binary trees
 
Binary tree
Binary treeBinary tree
Binary tree
 
Trees
TreesTrees
Trees
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
 
Data structures
Data structuresData structures
Data structures
 
Unit 8
Unit 8Unit 8
Unit 8
 
Unit – vi tree
Unit – vi   treeUnit – vi   tree
Unit – vi tree
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
 
Binary trees
Binary treesBinary trees
Binary trees
 
Lec6
Lec6Lec6
Lec6
 
Binary Search Tree Traversal.ppt
Binary Search Tree Traversal.pptBinary Search Tree Traversal.ppt
Binary Search Tree Traversal.ppt
 
Binary Trees.ppt
Binary Trees.pptBinary Trees.ppt
Binary Trees.ppt
 
Tree
TreeTree
Tree
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
 
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptxLecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
 
Binary tree
Binary treeBinary tree
Binary tree
 
Tree and Binary Search tree
Tree and Binary Search treeTree and Binary Search tree
Tree and Binary Search tree
 
Unit 3.ppt
Unit 3.pptUnit 3.ppt
Unit 3.ppt
 
Implementation of trees
Implementation of trees Implementation of trees
Implementation of trees
 

Mehr von Tech_MX

Virtual base class
Virtual base classVirtual base class
Virtual base class
Tech_MX
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
Tech_MX
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
Tech_MX
 
String & its application
String & its applicationString & its application
String & its application
Tech_MX
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
Tech_MX
 
Stack data structure
Stack data structureStack data structure
Stack data structure
Tech_MX
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
Tech_MX
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
Tech_MX
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
Tech_MX
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
Tech_MX
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
Tech_MX
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
Tech_MX
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
Tech_MX
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
Tech_MX
 
Linear regression
Linear regressionLinear regression
Linear regression
Tech_MX
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
Tech_MX
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
Tech_MX
 
Interpersonal communication
Interpersonal communicationInterpersonal communication
Interpersonal communication
Tech_MX
 
Interesting applications of graph theory
Interesting applications of graph theoryInteresting applications of graph theory
Interesting applications of graph theory
Tech_MX
 

Mehr von Tech_MX (20)

Virtual base class
Virtual base classVirtual base class
Virtual base class
 
Theory of estimation
Theory of estimationTheory of estimation
Theory of estimation
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
String & its application
String & its applicationString & its application
String & its application
 
Statistical quality__control_2
Statistical  quality__control_2Statistical  quality__control_2
Statistical quality__control_2
 
Stack data structure
Stack data structureStack data structure
Stack data structure
 
Stack Data Structure & It's Application
Stack Data Structure & It's Application Stack Data Structure & It's Application
Stack Data Structure & It's Application
 
Spanning trees & applications
Spanning trees & applicationsSpanning trees & applications
Spanning trees & applications
 
Real time Operating System
Real time Operating SystemReal time Operating System
Real time Operating System
 
Parsing
ParsingParsing
Parsing
 
Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)Mouse interrupts (Assembly Language & C)
Mouse interrupts (Assembly Language & C)
 
Motherboard of a pc
Motherboard of a pcMotherboard of a pc
Motherboard of a pc
 
MultiMedia dbms
MultiMedia dbmsMultiMedia dbms
MultiMedia dbms
 
Merging files (Data Structure)
Merging files (Data Structure)Merging files (Data Structure)
Merging files (Data Structure)
 
Memory dbms
Memory dbmsMemory dbms
Memory dbms
 
Linear regression
Linear regressionLinear regression
Linear regression
 
Keyboard interrupt
Keyboard interruptKeyboard interrupt
Keyboard interrupt
 
Introduction to loaders
Introduction to loadersIntroduction to loaders
Introduction to loaders
 
Interpersonal communication
Interpersonal communicationInterpersonal communication
Interpersonal communication
 
Interesting applications of graph theory
Interesting applications of graph theoryInteresting applications of graph theory
Interesting applications of graph theory
 

Kürzlich hochgeladen

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

09 binary-trees

  • 2. Parts of a binary tree  A binary tree is composed of zero or more nodes  Each node contains:  A value (some sort of data item)  A reference or pointer to a left child (may be null), and  A reference or pointer to a right child (may be null)  A binary tree may be empty (contain no nodes)  If not empty, a binary tree has a root node  Every node in the binary tree is reachable from the root node by a unique path  A node with neither a left child nor a right child is called a leaf  In some binary trees, only the leaves contain a value 2
  • 3. Picture of a binary tree a b c d e f g h i j k l 3
  • 4. Size and depth  The size of a binary tree is the a number of nodes in it  This tree has size 12 b c  The depth of a node is its distance from the root d e f  a is at depth zero  e is at depth 2 g h i j k  The depth of a binary tree is l the depth of its deepest node  This tree has depth 4 4
  • 5. Balance a a b c b c e d e f g d f h i j g h A balanced binary tree i j An unbalanced binary tree  A binary tree is balanced if every level above the lowest is “full” (contains 2n nodes)  In most applications, a reasonably balanced binary tree is desirable 5
  • 6. Binary search in an array  Look at array location (lo + hi)/2 Searching for 5: (0+6)/2 = 3 Using a binary hi = 2; (0 + 2)/2 = 1 lo = 2; search tree (2+2)/2=2 7 3 13 0 1 2 3 4 5 6 2 3 5 7 11 13 17 2 5 11 17 6
  • 7. Tree traversals  A binary tree is defined recursively: it consists of a root, a left subtree, and a right subtree  To traverse (or walk) the binary tree is to visit each node in the binary tree exactly once  Tree traversals are naturally recursive  Since a binary tree has three “parts,” there are six possible ways to traverse the binary tree:  root, right, left  root, left, right  right, root, left  left, root, right  right, left, root  left, right, root 7
  • 8. Preorder traversal  In preorder, the root is visited first  Here’s a preorder traversal to print out all the elements in the binary tree: public void preorderPrint(BinaryTree bt) { if (bt == null) return; System.out.println(bt.value); preorderPrint(bt.leftChild); preorderPrint(bt.rightChild); } 8
  • 9. Inorder traversal  In inorder, the root is visited in the middle  Here’s an inorder traversal to print out all the elements in the binary tree: public void inorderPrint(BinaryTree bt) { if (bt == null) return; inorderPrint(bt.leftChild); System.out.println(bt.value); inorderPrint(bt.rightChild); } 9
  • 10. Postorder traversal  In postorder, the root is visited last  Here’s a postorder traversal to print out all the elements in the binary tree: public void postorderPrint(BinaryTree bt) { if (bt == null) return; postorderPrint(bt.leftChild); postorderPrint(bt.rightChild); System.out.println(bt.value); } 10
  • 11. Tree traversals using “flags”  The order in which the nodes are visited during a tree traversal can be easily determined by imagining there is a “flag” attached to each node, as follows: preorder inorder postorder  To traverse the tree, collect the flags: A A A B C B C B C D E F G D E F G D E F G ABDECFG DBEAFCG DEBFGCA 11
  • 12. Copying a binary tree  In postorder, the root is visited last  Here’s a postorder traversal to make a complete copy of a given binary tree: public BinaryTree copyTree(BinaryTree bt) { if (bt == null) return null; BinaryTree left = copyTree(bt.leftChild); BinaryTree right = copyTree(bt.rightChild); return new BinaryTree(bt.value, left, right); } 12
  • 13. Other traversals  The other traversals are the reverse of these three standard ones  That is, the right subtree is traversed before the left subtree is traversed  Reverse preorder: root, right subtree, left subtree  Reverse inorder: right subtree, root, left subtree  Reverse postorder: right subtree, left subtree, root 13
  • 14. The End 14