SlideShare a Scribd company logo
Binary Trees Data Structures and Design in Java  © Rick Mercer
Why Trees?  Trees Tree Terminology Binary Trees One Recursive Tree Algorithm Outline
Storing Many Objects We  have examined 2 major ways to store data in the main memory of the computer arrays use subscripts to immediately access elements fast access, but in the old days would consume more memory that you would like it to (not true anymore) linked structures  each node refers to the next in the collection. To get to one you often traverse sequentially  maybe slower, but maybe manages memory better
Another Linked Structure We now turn our attention to another major way of storing data: the Tree One implementation of a  binary  tree has nodes with a left and right link field 1 3 2 root edges nodes
First Some Definitions A tree has a set of nodes and directed edges that connect them a directed edge connects a parent to its children Tree properties one node is distinguished as the root every node (except the root) is connected by an edge from exactly one other node A unique path traverses from the root to each node
General Trees Trees store data in a hierarchical manner Root node is A A's children are B, C, and D E, F, and D are leaves Length of path from A to E is 2 edges A D B C F E Trees have layers of nodes, where some are higher, others are lower.
Some tree terminology Node  An element in the tree  references data and other nodes Root  The node at the top  It is upside down! Parent  The node directly above another node (except root) Child  The node(s) below a given node Size  The number of descendants plus one for the node itself Leaves  Nodes with no children Levels  The root A is at level 0, E and F are at level 2
Applications of trees File Systems Hierarchical files systems include Unix and DOS In DOS, each \ represents an edge  (In Unix, it's /) Each directory is a file with a list of all its children Store large volumes of data data can be quickly inserted, removed, and found Data structure used in a variety of situations implement data vase management systems compilers: expression tree, symbol tree The Computer Science Department's new logo okay we're working on a new logo A tree
Binary Trees N-ary tree has n children max from each node A binary tree is a tree where all nodes have zero, one or two children  we'll study these binary trees only Each node is a leaf, has a right child, has a left child, or has both a left and right child A C B F D E
Binary Tree Defined A binary tree is either: an empty tree consists of a node, called a root, and zero, one, or two children (left and right), each of which are themselves binary trees This recursive definition uses the term "empty tree" as the base case Every non-empty node has two children, either of which may be empty On previous slide, C's left child is an empty tree.
Application: Expression Trees Binary trees can represent arithmetic expressions  An infix expression will have a parent operator and two children operands: - 1 + 3 * The expression: ((3+(7*2))-1) Each parenthesized expression becomes a tree. Each operand is a leaf, each operator is an internal node 7 2
Evaluating the Expression tree To evaluate the expression tree: Take any two leaves  Apply the parent's operator to them Replace that operator with the value of the subexpression.  * 3 + 2 4 * 3 6 18
Huffman Coding Tree Binary trees in a famous file compression algorithm  Huffman Coding Tree Each character is stored in a leaf The code is found by following the path 0 go left, 1 go right a is 01 e is 1 what is t? What is  0100100101 ? 'e' 't' 'a'
An inner class will be used to store one node of a binary tree private class BinaryTreeNode  {  // instance variables private Object data;  private BinaryTreeNode left; private BinaryTreeNode right; BinaryTreeNode() // This would be given to us  { data = null; left = null; right = null;  }
A Third Constructor BinaryTreeNode(Object theData)  {  // Used most often data = theData; left = null; right = null; }  BinaryTreeNode(Object theData, BinaryTreeNode leftLink,  BinaryTreeNode rightLink)  {  data  = theData; left  = leftLink; right = rightLink; } }  // end class BinaryTreeNode
class BinaryTreeNode Each  BinaryTreeNode  object has  a reference to an object  object so we can store anything a link to the left subtree  which could be an empty tree  a link to the right subtree  which could be an empty tree 3 Constructors  two set some data fields to  null  ( left  and  right ) The data fields are private Like  LinkNode , methods in the enclosing class can reference private instance variables of the inner class
Build a Tree with Three Nodes Hard code a tree referenced by root We do not yet have a nice way to insert new nodes This demonstrates linked  BinaryTreeNode  objects BinaryTreeNode root = new BinaryTreeNode("1"); root.left = new BinaryTreeNode("2"); root.right = new BinaryTreeNode("3"); "1" "3" "2" root
Recursion and Trees Trees are defined recursively and tree algorithms are implemented recursively For example, size  (all descendants plus 1) // call a size after building a tree System.out.println(size(root));  public int size(BinaryTreeNode t)  {  // return size of tree rooted at t What is the base case? (think simplest possibility) With trees, the recursive case often makes a recursive call on the left  subtree and another on the right subtree }
Active Learning 1) Draw this tree  BinaryTreeNode aTree = new BinaryTreeNode("1"); aTree.left = new BinaryTreeNode("2"); aTree.right = new BinaryTreeNode("3"); aTree.right.right = new BinaryTreeNode("4"); aTree.right.left = new BinaryTreeNode("5"); aTree.left.right = new BinaryTreeNode("6"); aTree.left.left = new BinaryTreeNode("7"); aTree.left.left.left = new BinaryTreeNode("8"); 2) Then write output generated  System.out.println(size(aTree)); // Of course you could keep track of  // size as another instance variable

More Related Content

What's hot (20)

PPTX
Binary Search Tree
sagar yadav
 
PPTX
Tree Traversal
Md. Israil Fakir
 
PPTX
Terminology of tree
RacksaviR
 
PPT
UNIT-4 TREES.ppt
SIVAKUMARM603675
 
PPTX
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
PPTX
Recursion
Nalin Adhikari
 
PDF
Binary search algorithm
maamir farooq
 
PDF
Binary tree
Rajendran
 
PDF
Packages - PL/SQL
Esmita Gupta
 
PPTX
Linked list in Data Structure and Algorithm
KristinaBorooah
 
PPTX
Skip lists (Advance Data structure)
Shubham Shukla
 
PPTX
Binary Tree in Data Structure
Meghaj Mallick
 
PPTX
Pointer in C++
Mauryasuraj98
 
PPTX
Decomposition methods in DBMS
soniyagoyal3
 
PPTX
Data structures
Sneha Chopra
 
PPTX
Xml dtd
HeenaRajput1
 
PPTX
Stack and Queue
Apurbo Datta
 
PPTX
Dfs
Ashish Ranjan
 
PDF
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
PPT
Binary search tree(bst)
Hossain Md Shakhawat
 
Binary Search Tree
sagar yadav
 
Tree Traversal
Md. Israil Fakir
 
Terminology of tree
RacksaviR
 
UNIT-4 TREES.ppt
SIVAKUMARM603675
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
Muhammad Hammad Waseem
 
Recursion
Nalin Adhikari
 
Binary search algorithm
maamir farooq
 
Binary tree
Rajendran
 
Packages - PL/SQL
Esmita Gupta
 
Linked list in Data Structure and Algorithm
KristinaBorooah
 
Skip lists (Advance Data structure)
Shubham Shukla
 
Binary Tree in Data Structure
Meghaj Mallick
 
Pointer in C++
Mauryasuraj98
 
Decomposition methods in DBMS
soniyagoyal3
 
Data structures
Sneha Chopra
 
Xml dtd
HeenaRajput1
 
Stack and Queue
Apurbo Datta
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Gurukul Kangri Vishwavidyalaya - Faculty of Engineering and Technology
 
Binary search tree(bst)
Hossain Md Shakhawat
 

Similar to Trees - Data structures in C/Java (20)

PPT
358 33 powerpoint-slides_10-trees_chapter-10
sumitbardhan
 
PPT
Tree 11.ppt
DEEPAK948083
 
PPTX
Data Structures -Non Linear DS-Basics ofTrees
sailaja156145
 
PDF
8.haftajava notlarıiçeriyordökumanlar.pdf
Smeyyeztrk10
 
PPT
Final tree.ppt tells about tree presentation
nakulvarshney371
 
PDF
Tree terminology and introduction to binary tree
jyoti_lakhani
 
PPT
Tree
sbkbca
 
PPTX
NON-LINEAR DATA STRUCTURE-TREES.pptx
Rajitha Reddy Alugati
 
PPTX
UNIT III Non Linear Data Structures - Trees.pptx
VISWANATHAN R V
 
PPT
Lecture 5 tree.pptx
Abirami A
 
PPTX
TREE PRESENTATION COMPUTER SCIENCE/DATA STRUCTURE
HaroldOmega1
 
PDF
Module - 5_Trees.pdf
AnuradhaJadiya1
 
PPTX
Tree.pptx
worldchannel
 
PPT
Data Structures 4
Dr.Umadevi V
 
PPTX
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
resming1
 
PPTX
UNIT III Non Linear Data Structures - Trees.pptx
kncetaruna
 
PPTX
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
HamzaUsman48
 
PPTX
Unit 5 Tree.pptx
SurajSharma266169
 
PPTX
Tree Data Structure Tree Data Structure Details
ssusera8c91a
 
PPT
Unit 3.ppt
JITTAYASHWANTHREDDY
 
358 33 powerpoint-slides_10-trees_chapter-10
sumitbardhan
 
Tree 11.ppt
DEEPAK948083
 
Data Structures -Non Linear DS-Basics ofTrees
sailaja156145
 
8.haftajava notlarıiçeriyordökumanlar.pdf
Smeyyeztrk10
 
Final tree.ppt tells about tree presentation
nakulvarshney371
 
Tree terminology and introduction to binary tree
jyoti_lakhani
 
Tree
sbkbca
 
NON-LINEAR DATA STRUCTURE-TREES.pptx
Rajitha Reddy Alugati
 
UNIT III Non Linear Data Structures - Trees.pptx
VISWANATHAN R V
 
Lecture 5 tree.pptx
Abirami A
 
TREE PRESENTATION COMPUTER SCIENCE/DATA STRUCTURE
HaroldOmega1
 
Module - 5_Trees.pdf
AnuradhaJadiya1
 
Tree.pptx
worldchannel
 
Data Structures 4
Dr.Umadevi V
 
Data Structures Module 3 Binary Trees Binary Search Trees Tree Traversals AVL...
resming1
 
UNIT III Non Linear Data Structures - Trees.pptx
kncetaruna
 
Lecture-7-Binary-Trees-and-Algorithms-11052023-054009pm.pptx
HamzaUsman48
 
Unit 5 Tree.pptx
SurajSharma266169
 
Tree Data Structure Tree Data Structure Details
ssusera8c91a
 
Ad

Recently uploaded (20)

PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Biography of Daniel Podor.pdf
Daniel Podor
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
July Patch Tuesday
Ivanti
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Ad

Trees - Data structures in C/Java

  • 1. Binary Trees Data Structures and Design in Java © Rick Mercer
  • 2. Why Trees? Trees Tree Terminology Binary Trees One Recursive Tree Algorithm Outline
  • 3. Storing Many Objects We have examined 2 major ways to store data in the main memory of the computer arrays use subscripts to immediately access elements fast access, but in the old days would consume more memory that you would like it to (not true anymore) linked structures each node refers to the next in the collection. To get to one you often traverse sequentially maybe slower, but maybe manages memory better
  • 4. Another Linked Structure We now turn our attention to another major way of storing data: the Tree One implementation of a binary tree has nodes with a left and right link field 1 3 2 root edges nodes
  • 5. First Some Definitions A tree has a set of nodes and directed edges that connect them a directed edge connects a parent to its children Tree properties one node is distinguished as the root every node (except the root) is connected by an edge from exactly one other node A unique path traverses from the root to each node
  • 6. General Trees Trees store data in a hierarchical manner Root node is A A's children are B, C, and D E, F, and D are leaves Length of path from A to E is 2 edges A D B C F E Trees have layers of nodes, where some are higher, others are lower.
  • 7. Some tree terminology Node An element in the tree references data and other nodes Root The node at the top It is upside down! Parent The node directly above another node (except root) Child The node(s) below a given node Size The number of descendants plus one for the node itself Leaves Nodes with no children Levels The root A is at level 0, E and F are at level 2
  • 8. Applications of trees File Systems Hierarchical files systems include Unix and DOS In DOS, each \ represents an edge (In Unix, it's /) Each directory is a file with a list of all its children Store large volumes of data data can be quickly inserted, removed, and found Data structure used in a variety of situations implement data vase management systems compilers: expression tree, symbol tree The Computer Science Department's new logo okay we're working on a new logo A tree
  • 9. Binary Trees N-ary tree has n children max from each node A binary tree is a tree where all nodes have zero, one or two children we'll study these binary trees only Each node is a leaf, has a right child, has a left child, or has both a left and right child A C B F D E
  • 10. Binary Tree Defined A binary tree is either: an empty tree consists of a node, called a root, and zero, one, or two children (left and right), each of which are themselves binary trees This recursive definition uses the term "empty tree" as the base case Every non-empty node has two children, either of which may be empty On previous slide, C's left child is an empty tree.
  • 11. Application: Expression Trees Binary trees can represent arithmetic expressions An infix expression will have a parent operator and two children operands: - 1 + 3 * The expression: ((3+(7*2))-1) Each parenthesized expression becomes a tree. Each operand is a leaf, each operator is an internal node 7 2
  • 12. Evaluating the Expression tree To evaluate the expression tree: Take any two leaves Apply the parent's operator to them Replace that operator with the value of the subexpression. * 3 + 2 4 * 3 6 18
  • 13. Huffman Coding Tree Binary trees in a famous file compression algorithm Huffman Coding Tree Each character is stored in a leaf The code is found by following the path 0 go left, 1 go right a is 01 e is 1 what is t? What is 0100100101 ? 'e' 't' 'a'
  • 14. An inner class will be used to store one node of a binary tree private class BinaryTreeNode { // instance variables private Object data; private BinaryTreeNode left; private BinaryTreeNode right; BinaryTreeNode() // This would be given to us { data = null; left = null; right = null; }
  • 15. A Third Constructor BinaryTreeNode(Object theData) { // Used most often data = theData; left = null; right = null; } BinaryTreeNode(Object theData, BinaryTreeNode leftLink, BinaryTreeNode rightLink) { data = theData; left = leftLink; right = rightLink; } } // end class BinaryTreeNode
  • 16. class BinaryTreeNode Each BinaryTreeNode object has a reference to an object object so we can store anything a link to the left subtree which could be an empty tree a link to the right subtree which could be an empty tree 3 Constructors two set some data fields to null ( left and right ) The data fields are private Like LinkNode , methods in the enclosing class can reference private instance variables of the inner class
  • 17. Build a Tree with Three Nodes Hard code a tree referenced by root We do not yet have a nice way to insert new nodes This demonstrates linked BinaryTreeNode objects BinaryTreeNode root = new BinaryTreeNode("1"); root.left = new BinaryTreeNode("2"); root.right = new BinaryTreeNode("3"); "1" "3" "2" root
  • 18. Recursion and Trees Trees are defined recursively and tree algorithms are implemented recursively For example, size (all descendants plus 1) // call a size after building a tree System.out.println(size(root)); public int size(BinaryTreeNode t) { // return size of tree rooted at t What is the base case? (think simplest possibility) With trees, the recursive case often makes a recursive call on the left subtree and another on the right subtree }
  • 19. Active Learning 1) Draw this tree BinaryTreeNode aTree = new BinaryTreeNode("1"); aTree.left = new BinaryTreeNode("2"); aTree.right = new BinaryTreeNode("3"); aTree.right.right = new BinaryTreeNode("4"); aTree.right.left = new BinaryTreeNode("5"); aTree.left.right = new BinaryTreeNode("6"); aTree.left.left = new BinaryTreeNode("7"); aTree.left.left.left = new BinaryTreeNode("8"); 2) Then write output generated System.out.println(size(aTree)); // Of course you could keep track of // size as another instance variable