SlideShare a Scribd company logo
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 AVL
Katang Isip
 
Binary searchtrees
Binary searchtreesBinary searchtrees
Binary searchtrees
Xavient Information Systems
 
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
Anton 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-bddicken
Benjamin Dicken
 
ch5
ch5ch5
1.5 binary search tree
1.5 binary search tree1.5 binary search tree
1.5 binary search tree
Krish_ver2
 
Software engineering
Software engineeringSoftware engineering
Software engineering
Dulaj Nuwansiri
 
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
Zafar 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 trees
zukun
 
07slide
07slide07slide
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro 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_v3
Hariz Mustafa
 
Chapter 5 ds
Chapter 5 dsChapter 5 ds
Chapter 5 ds
Hanif Durad
 
Chapter 3 ds
Chapter 3 dsChapter 3 ds
Chapter 3 ds
Hanif Durad
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro 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

L 19 ct1120
L 19 ct1120L 19 ct1120
L 19 ct1120
Zia Ush Shamszaman
 
Mca admission in india
Mca admission in indiaMca admission in india
Mca admission in india
Edhole.com
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
RashidFaridChishti
 
Lecture_10 - Revised.pptx
Lecture_10 - Revised.pptxLecture_10 - Revised.pptx
Lecture_10 - Revised.pptx
RedHeart11
 
Binary trees
Binary treesBinary trees
Binary trees
Ssankett Negi
 
Decision tree handson
Decision tree handsonDecision tree handson
Decision tree handson
Shyam 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.pdf
fathimaoptical
 
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
farrahkur54
 
Biary search Tree.docx
Biary search Tree.docxBiary search Tree.docx
Biary search Tree.docx
sowmya koneru
 
Topic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.pptTopic19BinarySearchTrees.ppt
Topic19BinarySearchTrees.ppt
plagcheck
 
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
Footageetoffe16
 
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
hadpadrrajeshh
 
Running Head Discussion Board .docx
Running Head Discussion Board                                  .docxRunning Head Discussion Board                                  .docx
Running Head Discussion Board .docx
jeanettehully
 
Tree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy CollectionsTree Leetcode - Interview Questions - Easy Collections
Tree Leetcode - Interview Questions - Easy Collections
Sunil 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.docx
festockton
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
maznabili
 
computer notes - Data Structures - 13
computer notes - Data Structures - 13computer notes - Data Structures - 13
computer notes - Data Structures - 13
ecomputernotes
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
Sriram Raj
 
lecture 12
lecture 12lecture 12
lecture 12
sajinsc
 
Tree
TreeTree

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
 
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptxData Structures and Agorithm: DS 10 Binary Search Tree.pptx
Data Structures and Agorithm: DS 10 Binary Search Tree.pptx
 
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
 

More from Mohamed Elsayed

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

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

World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
Celine George
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 

Recently uploaded (20)

World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
How to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRMHow to Manage Your Lost Opportunities in Odoo 17 CRM
How to Manage Your Lost Opportunities in Odoo 17 CRM
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 

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