SlideShare a Scribd company logo
1 of 18
Download to read offline
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Binary Trees:
Practice Problems
Binary Trees: Practice Problems page 2
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Warmup Problem 1: Searching for a node
public boolean recursiveSearch(int data) {
return(recursiveSearch(root, data));
}
private boolean recursiveSearch(intBSTnode p, int data) {
if (p == null) { // meaning, there is no node!
return(false);
}
if (data == p.data) {
return(true);
}
else if (data < p.data) {
return(recursiveSearch(p.left, data));
}
else {
return(recursiveSearch(p.right, data));
}
}
Binary Trees: Practice Problems page 3
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Warmup Problem 2:
 Searching for a node in an arbitrary tree
 Not a BST…Doesn’t have the ordering property
public boolean searchTree(int data) {
return(searchTree(root, data));
}
private boolean searchTree(intBSTnode p, int data) {
if (p == null) { // meaning, there is no node!
return(false);
}
if (data == p.data) {
return(true);
}
return (searchTree(p.left, data) || searchTree(p.right, data));
}
Binary Trees: Practice Problems page 4
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Warmup Problem 3:
 Summing the values of nodes in a tree
public int sumNodes() {
return(sumNodes(root));
}
private int sumNodes(intBSTnode p) {
if (p == null)
return(0);
else {
return p.data + sumNodes(p.left) + sumNodes(p.right);
}
}
Binary Trees: Practice Problems page 5
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Count Nodes:
 Write a method that counts (and returns) the
number of nodes in a binary tree
public int countNodes() {
return(countNodes(root));
}
private int countNodes(intBSTnode p) {
if (p == null)
return(0);
else {
return 1 + countNodes(p.left) + countNodes(p.right);
}
}
Binary Trees: Practice Problems page 6
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Count Leaf Nodes:
 Write a method that counts (and returns) the
number of leaf nodes in a binary tree
public int numLeaves () {
return(numLeaves(root));
}
public int numLeaves(intBSTnode p) {
if (p != NULL) {
if (p.left == NULL && p.right == NULL)
return 1;
else
return numLeaves(p.left) + numLeaves(p.right);
}
else
return 0;
}
Binary Trees: Practice Problems page 7
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Print Even Nodes:
 Write a method that prints out all even nodes in a
binary search tree
 This is basically just a traversal
 Except we added a condition (IF) statement before the
print statement
private void printEven(intBSTnode p) {
if (p != null) {
if (p.data % 2 == 0)
System.out.print(p.data + “ ”);
printEven(p.left);
printEven(p.right);
}
}
Binary Trees: Practice Problems page 8
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Print Odd Nodes (in ascending order):
 Write a function that prints out all odd nodes, in a
binary search tree, in ascending order
 The question requested ascending order
 This requires an inorder traversal
 So we simply changed the order of the statements
private void printOddAsc(intBSTnode p) {
if (p != null) {
printOddAsc(p.left);
if (p.data % 2 == 1)
System.out.print(p.data + “ ”);
printOddAsc(p.right);
}
}
Binary Trees: Practice Problems page 9
© Dr. Jonathan (Yahya) Cazalas
Brief Interlude: FAIL Picture
Binary Trees: Practice Problems page 10
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Compute Height:
 Write a recursive method to compute the height of a
tree
 Defined as the length of the longest path from the root to a
leaf node
 For the purposes of this problem,
 a tree with only one node has height 1
 and an empty tree has height 0
Binary Trees: Practice Problems page 11
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Compute Height:
private int height(intBSTnode root) {
int leftHeight, rightHeight;
if (root == null)
return 0;
leftHeight = height(root.left);
rightHeight = height(root.right);
if (leftHeight > rightHeight)
return leftHeight + 1;
return rightHeight + 1;
}
Binary Trees: Practice Problems page 12
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Find Largest:
 Write a recursive method that returns a pointer to
the node containing the largest element in a BST
 This one should be easy:
 This is a BST, meaning it has the ordering property
 So where is the largest node located
 either the root or the greatest node in the right subtree
Binary Trees: Practice Problems page 13
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Find Largest:
private intBSTnode largest(intBSTnode B) {
// if B is NULL, there is no node
if (B == null)
return null;
// If B’s right is NULL, that means B is the largest
else if (B.right == null)
return B;
// SO if B’s right was NOT equal to NULL,
// There is a right subtree of B.
// Which means that the largest value is in this
// subtree. So recursively call B’s right.
else
return largest(B.right);
}
Binary Trees: Practice Problems page 14
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Number of Single Children:
 In a binary tree, each node can have zero, one, or
two children
 Write a recursive method that returns the number of
nodes with a single child
Binary Trees: Practice Problems page 15
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
 Number of Single Children:
public int one(intBSTnode p) {
if (p != NULL) {
if (p.left == null)
if (p.right != null)
return 1 + one(p.right);
else if (p.right == null)
if (p.left != null)
return 1 + one(p.left);
else
return one(p.left) + one(p.right);
}
}
Binary Trees: Practice Problems page 16
© Dr. Jonathan (Yahya) Cazalas
Binary Trees: Practice Problems
WASN’T
THAT
SPICY!
Binary Trees: Practice Problems page 17
© Dr. Jonathan (Yahya) Cazalas
Daily Demotivator
College of Computing & Information Technology
King Abdulaziz University
CPCS-204 – Data Structures I
Binary Trees:
Practice Problems

More Related Content

What's hot

Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVLKatang Isip
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsAnton Astashov
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)Trupti Agrawal
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)amna izzat
 
BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddickenBenjamin Dicken
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search treeKrish_ver2
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeZafar Ayub
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treeszukun
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Hariz Mustafa
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 

What's hot (20)

Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
 
Immutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScriptsImmutability, and how to do it in JavaScripts
Immutability, and how to do it in JavaScripts
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Week 8 (trees)
Week 8 (trees)Week 8 (trees)
Week 8 (trees)
 
BinarySearchTree-bddicken
BinarySearchTree-bddickenBinarySearchTree-bddicken
BinarySearchTree-bddicken
 
ch5
ch5ch5
ch5
 
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
 
Software engineering
Software engineeringSoftware engineering
Software engineering
 
BINARY SEARCH TREE
BINARY SEARCH TREEBINARY SEARCH TREE
BINARY SEARCH TREE
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Skiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure treesSkiena algorithm 2007 lecture05 dictionary data structure trees
Skiena algorithm 2007 lecture05 dictionary data structure trees
 
07slide
07slide07slide
07slide
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3Lecture07 the linked-list_as_a_data_structure_v3
Lecture07 the linked-list_as_a_data_structure_v3
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 

Similar to binary_trees4

Mca admission in india
Mca admission in indiaMca admission in india
Mca admission in indiaEdhole.com
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptxRedHeart11
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handsonShyam Sarkar
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdffathimaoptical
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxfarrahkur54
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docxsowmya koneru
 
Topic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptTopic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptplagcheck
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfFootageetoffe16
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfhadpadrrajeshh
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docxjeanettehully
 
Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsSunil Yadav
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxfestockton
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
computer notes - Data Structures - 13
computer notes - Data Structures - 13computer notes - Data Structures - 13
computer notes - Data Structures - 13ecomputernotes
 
lecture 12
lecture 12lecture 12
lecture 12sajinsc
 

Similar to binary_trees4 (20)

L 19 ct1120
L 19 ct1120L 19 ct1120
L 19 ct1120
 
Mca admission in india
Mca admission in indiaMca admission in india
Mca admission in india
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
 
Binary trees
Binary treesBinary trees
Binary trees
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
 
Modify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdfModify this code to do an Insert function for an AVL tree, instead o.pdf
Modify this code to do an Insert function for an AVL tree, instead o.pdf
 
Once you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docxOnce you have all the structures working as intended- it is time to co.docx
Once you have all the structures working as intended- it is time to co.docx
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
 
Topic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptTopic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.ppt
 
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdfAssignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
Assignment 9 (Parent reference for BST) Redefine TreeNode by adding .pdf
 
Given a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdfGiven a newly created Binary Search Tree with the following numerica.pdf
Given a newly created Binary Search Tree with the following numerica.pdf
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docx
 
Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy Collections
 
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docxAssg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
Assg 12 Binary Search TreesCOSC 2336 Spring 2019April.docx
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
computer notes - Data Structures - 13
computer notes - Data Structures - 13computer notes - Data Structures - 13
computer notes - Data Structures - 13
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
 
lecture 12
lecture 12lecture 12
lecture 12
 
Tree
TreeTree
Tree
 
Tree
TreeTree
Tree
 

More from Mohamed Elsayed (20)

binary_trees1
binary_trees1binary_trees1
binary_trees1
 
queues
queuesqueues
queues
 
stacks2
stacks2stacks2
stacks2
 
stacks1
stacks1stacks1
stacks1
 
algorithm_analysis2
algorithm_analysis2algorithm_analysis2
algorithm_analysis2
 
algorithm_analysis1
algorithm_analysis1algorithm_analysis1
algorithm_analysis1
 
recursion2
recursion2recursion2
recursion2
 
recursion1
recursion1recursion1
recursion1
 
linked_lists4
linked_lists4linked_lists4
linked_lists4
 
linked_lists3
linked_lists3linked_lists3
linked_lists3
 
Linked_lists2
Linked_lists2Linked_lists2
Linked_lists2
 
linked_lists
linked_listslinked_lists
linked_lists
 
sorted_listmatch
sorted_listmatchsorted_listmatch
sorted_listmatch
 
arrays
arraysarrays
arrays
 
introduction
introductionintroduction
introduction
 
heaps2
heaps2heaps2
heaps2
 
heaps
heapsheaps
heaps
 
hash_tables
hash_tableshash_tables
hash_tables
 
graphs
graphsgraphs
graphs
 
quick_sort
quick_sortquick_sort
quick_sort
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 

binary_trees4

  • 1. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Binary Trees: Practice Problems
  • 2. Binary Trees: Practice Problems page 2 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Warmup Problem 1: Searching for a node public boolean recursiveSearch(int data) { return(recursiveSearch(root, data)); } private boolean recursiveSearch(intBSTnode p, int data) { if (p == null) { // meaning, there is no node! return(false); } if (data == p.data) { return(true); } else if (data < p.data) { return(recursiveSearch(p.left, data)); } else { return(recursiveSearch(p.right, data)); } }
  • 3. Binary Trees: Practice Problems page 3 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Warmup Problem 2:  Searching for a node in an arbitrary tree  Not a BST…Doesn’t have the ordering property public boolean searchTree(int data) { return(searchTree(root, data)); } private boolean searchTree(intBSTnode p, int data) { if (p == null) { // meaning, there is no node! return(false); } if (data == p.data) { return(true); } return (searchTree(p.left, data) || searchTree(p.right, data)); }
  • 4. Binary Trees: Practice Problems page 4 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Warmup Problem 3:  Summing the values of nodes in a tree public int sumNodes() { return(sumNodes(root)); } private int sumNodes(intBSTnode p) { if (p == null) return(0); else { return p.data + sumNodes(p.left) + sumNodes(p.right); } }
  • 5. Binary Trees: Practice Problems page 5 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Count Nodes:  Write a method that counts (and returns) the number of nodes in a binary tree public int countNodes() { return(countNodes(root)); } private int countNodes(intBSTnode p) { if (p == null) return(0); else { return 1 + countNodes(p.left) + countNodes(p.right); } }
  • 6. Binary Trees: Practice Problems page 6 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Count Leaf Nodes:  Write a method that counts (and returns) the number of leaf nodes in a binary tree public int numLeaves () { return(numLeaves(root)); } public int numLeaves(intBSTnode p) { if (p != NULL) { if (p.left == NULL && p.right == NULL) return 1; else return numLeaves(p.left) + numLeaves(p.right); } else return 0; }
  • 7. Binary Trees: Practice Problems page 7 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Print Even Nodes:  Write a method that prints out all even nodes in a binary search tree  This is basically just a traversal  Except we added a condition (IF) statement before the print statement private void printEven(intBSTnode p) { if (p != null) { if (p.data % 2 == 0) System.out.print(p.data + “ ”); printEven(p.left); printEven(p.right); } }
  • 8. Binary Trees: Practice Problems page 8 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Print Odd Nodes (in ascending order):  Write a function that prints out all odd nodes, in a binary search tree, in ascending order  The question requested ascending order  This requires an inorder traversal  So we simply changed the order of the statements private void printOddAsc(intBSTnode p) { if (p != null) { printOddAsc(p.left); if (p.data % 2 == 1) System.out.print(p.data + “ ”); printOddAsc(p.right); } }
  • 9. Binary Trees: Practice Problems page 9 © Dr. Jonathan (Yahya) Cazalas Brief Interlude: FAIL Picture
  • 10. Binary Trees: Practice Problems page 10 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Compute Height:  Write a recursive method to compute the height of a tree  Defined as the length of the longest path from the root to a leaf node  For the purposes of this problem,  a tree with only one node has height 1  and an empty tree has height 0
  • 11. Binary Trees: Practice Problems page 11 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Compute Height: private int height(intBSTnode root) { int leftHeight, rightHeight; if (root == null) return 0; leftHeight = height(root.left); rightHeight = height(root.right); if (leftHeight > rightHeight) return leftHeight + 1; return rightHeight + 1; }
  • 12. Binary Trees: Practice Problems page 12 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Find Largest:  Write a recursive method that returns a pointer to the node containing the largest element in a BST  This one should be easy:  This is a BST, meaning it has the ordering property  So where is the largest node located  either the root or the greatest node in the right subtree
  • 13. Binary Trees: Practice Problems page 13 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Find Largest: private intBSTnode largest(intBSTnode B) { // if B is NULL, there is no node if (B == null) return null; // If B’s right is NULL, that means B is the largest else if (B.right == null) return B; // SO if B’s right was NOT equal to NULL, // There is a right subtree of B. // Which means that the largest value is in this // subtree. So recursively call B’s right. else return largest(B.right); }
  • 14. Binary Trees: Practice Problems page 14 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Number of Single Children:  In a binary tree, each node can have zero, one, or two children  Write a recursive method that returns the number of nodes with a single child
  • 15. Binary Trees: Practice Problems page 15 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems  Number of Single Children: public int one(intBSTnode p) { if (p != NULL) { if (p.left == null) if (p.right != null) return 1 + one(p.right); else if (p.right == null) if (p.left != null) return 1 + one(p.left); else return one(p.left) + one(p.right); } }
  • 16. Binary Trees: Practice Problems page 16 © Dr. Jonathan (Yahya) Cazalas Binary Trees: Practice Problems WASN’T THAT SPICY!
  • 17. Binary Trees: Practice Problems page 17 © Dr. Jonathan (Yahya) Cazalas Daily Demotivator
  • 18. College of Computing & Information Technology King Abdulaziz University CPCS-204 – Data Structures I Binary Trees: Practice Problems