SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Lecture7 data structure(tree)
Lecture7 data structure(tree)Lecture7 data structure(tree)
Lecture7 data structure(tree)
Taibah University, College of Computer Science & Engineering
 
Tree and binary tree
Tree and binary treeTree and binary tree
Tree and binary tree
Zaid Shabbir
 
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
Siddhi Shrivas
 
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
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Trees
TreesTrees
Trees
9590133127
 
Tree-In Data Structure
Tree-In Data StructureTree-In Data Structure
Tree-In Data Structure
United International University
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
Katang Isip
 
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
 
Chap 7 binary threaded tree
Chap 7 binary threaded treeChap 7 binary threaded tree
Chap 7 binary threaded tree
Raj Sarode
 
DATA STRUCTURES
DATA STRUCTURESDATA STRUCTURES
DATA STRUCTURES
bca2010
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
Sadaf Ismail
 
Data structure tree- advance
Data structure tree- advanceData structure tree- advance
Data structure tree- advance
MD. MARUFUZZAMAN .
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
Zafar Ayub
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
Saurabh Mishra
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
Syed Zaid Irshad
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
Krish_ver2
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
ER Punit Jain
 
binary search tree
binary search treebinary search tree
binary search tree
Shankar Bishnoi
 
Tree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal KhanTree Data Structure by Daniyal Khan
Tree Data Structure by Daniyal Khan
Daniyal Khan
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
Radhika Puttewar
 

Viewers also liked (19)

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
 
Linkers
LinkersLinkers
Linkers
Tech_MX
 
Uid
UidUid
Uid
Tech_MX
 
Spss
SpssSpss
Spss
Tech_MX
 
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
 
Ad

Similar to 09 binary-trees (20)

Binary trees
Binary treesBinary trees
Binary trees
Simratpreet Singh
 
Binary tree
Binary treeBinary tree
Binary tree
baabtra.com - No. 1 supplier of quality freshers
 
Trees
TreesTrees
Trees
noraidawati
 
Chapter 5_Trees.pdf
Chapter 5_Trees.pdfChapter 5_Trees.pdf
Chapter 5_Trees.pdf
ssuser50179b
 
Data structures
Data structuresData structures
Data structures
IIUI
 
Unit 8
Unit 8Unit 8
Unit 8
mrecedu
 
Unit – vi tree
Unit – vi   treeUnit – vi   tree
Unit – vi tree
Tribhuvan University
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
shameen khan
 
Unit 6 tree
Unit   6 treeUnit   6 tree
Unit 6 tree
Dabbal Singh Mahara
 
Binary trees
Binary treesBinary trees
Binary trees
Rajendran
 
Lec6
Lec6Lec6
Lec6
Anjneya Varshney
 
Binary Search Tree Traversal.ppt
Binary Search Tree Traversal.pptBinary Search Tree Traversal.ppt
Binary Search Tree Traversal.ppt
Riannel Tecson
 
Binary Trees.ppt
Binary Trees.pptBinary Trees.ppt
Binary Trees.ppt
Riannel Tecson
 
Tree
TreeTree
Tree
Abhishek Pachisia
 
binary tree.pptx
binary tree.pptxbinary tree.pptx
binary tree.pptx
DhanushSrinivasulu
 
Why Tree is considered a non-linear data structure?
Why Tree is considered a non-linear data structure?Why Tree is considered a non-linear data structure?
Why Tree is considered a non-linear data structure?
mominkainat05
 
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
HamzaUsman48
 
Weak 13 Trees, BST update.pptxhjjujjjhhhy
Weak 13 Trees, BST update.pptxhjjujjjhhhyWeak 13 Trees, BST update.pptxhjjujjjhhhy
Weak 13 Trees, BST update.pptxhjjujjjhhhy
baloch4551701
 
Binary tree
Binary treeBinary tree
Binary tree
Rajendran
 
Binary search Tree and avl tree , treee.ppt
Binary search Tree and avl tree , treee.pptBinary search Tree and avl tree , treee.ppt
Binary search Tree and avl tree , treee.ppt
sjain87654321
 
Ad

More from Tech_MX (20)

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
 
Parsing
ParsingParsing
Parsing
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
 
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
 

Recently uploaded (20)

MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
MULTI-STAKEHOLDER CONSULTATION PROGRAM On Implementation of DNF 2.0 and Way F...
ICT Frame Magazine Pvt. Ltd.
 
Scientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal DomainsScientific Large Language Models in Multi-Modal Domains
Scientific Large Language Models in Multi-Modal Domains
syedanidakhader1
 
AI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández VallejoAI and Meaningful Work by Pablo Fernández Vallejo
AI and Meaningful Work by Pablo Fernández Vallejo
UXPA Boston
 
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdfComputer Systems Quiz Presentation in Purple Bold Style (4).pdf
Computer Systems Quiz Presentation in Purple Bold Style (4).pdf
fizarcse
 
React Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for SuccessReact Native for Business Solutions: Building Scalable Apps for Success
React Native for Business Solutions: Building Scalable Apps for Success
Amelia Swank
 
Understanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdfUnderstanding SEO in the Age of AI.pdf
Understanding SEO in the Age of AI.pdf
Fulcrum Concepts, LLC
 
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Whose choice? Making decisions with and about Artificial Intelligence, Keele ...
Alan Dix
 
Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.Is Your QA Team Still Working in Silos? Here's What to Do.
Is Your QA Team Still Working in Silos? Here's What to Do.
marketing943205
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UX for Data Engineers and Analysts-Designing User-Friendly Dashboards for Non...
UXPA Boston
 
Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025Top 5 Qualities to Look for in Salesforce Partners in 2025
Top 5 Qualities to Look for in Salesforce Partners in 2025
Damco Salesforce Services
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Secondary Storage for a microcontroller system
Secondary Storage for a microcontroller systemSecondary Storage for a microcontroller system
Secondary Storage for a microcontroller system
fizarcse
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
Accommodating Neurodiverse Users Online (Global Accessibility Awareness Day 2...
User Vision
 
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
Longitudinal Benchmark: A Real-World UX Case Study in Onboarding by Linda Bor...
UXPA Boston
 
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptxIn-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
In-App Guidance_ Save Enterprises Millions in Training & IT Costs.pptx
aptyai
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Building Connected Agents:  An Overview of Google's ADK and A2A ProtocolBuilding Connected Agents:  An Overview of Google's ADK and A2A Protocol
Building Connected Agents: An Overview of Google's ADK and A2A Protocol
Suresh Peiris
 

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
  翻译: