A method “countLeftNodes()”
Program plan:
- Define the method “countLeftNodes()”,
- Return the value returned from the parameterized method “countLeftNodes()”.
- Define the parameterized method “countLeftNodes()”,
- Check whether the root of the tree is null,
- If it is true, return “0”.
- Otherwise, check whether the left node of the tree is null,
- Return the value returned from the parameterized method “countLeftNodes()”.
- Otherwise, return the calculated value.
- Otherwise, check whether the left node of the tree is null,
- If it is true, return “0”.
- Check whether the root of the tree is null,
This program demonstrates the method “countLeftNodes()” that return the number of left children in the tree.
Explanation of Solution
Code:
//Define the method
public int countLeftNodes()
{
/*Return the value returned from the parameterized method "countLeftNodes()"*/
return countLeftNodes(overallRoot);
}
//Define the parameterized method method "countLeftNodes()"
private int countLeftNodes(IntTreeNode root1)
{
//Check whether the root is null
if (root1 == null)
{
//Return "0"
return 0;
}
/*Otherwise, check whether the left node of the tree is null*/
else if (root1.left == null)
{
/*Return the value returned from the parameterized method "countLeftNodes()"*/
return countLeftNodes(root1.right);
}
else
{
//Return the calculated value
return 1 + countLeftNodes(root1.left) + countLeftNodes(root1.right);
}
}
Want to see more full solutions like this?
Chapter 17 Solutions
Building Java Programs: A Back To Basics Approach (5th Edition)
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education