SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Binary Trees
Exercise:
Exercises
Question:12 | ISBN:9780136091813 | Edition: 2

Question

Write a method called numberNodes that changes the data stored in a binary tree, assigning sequential integers starting with 1 to each node so that a preorder traversal will produce the numbers in order ( 1, 2, 3, etc). For example, if a variable t refers to reference tree #1, the call of t.numberNodes(); would overwrite the existing data, assigning values from 1 to 6 to the nodes so that a preorder traversal of the tree would produce 1, 2, 3, 4, 5, 6 as shown in the following diagram. Do not change the structure of the tree, only the values stored in the data fields.

Your method should return the number of nodes in the tree.

 

 

 

 

 

 

 

Add the above method to the IntTree class from this chapter. You may define additional private methods to implement your public method if necessary. Several problem descriptions refer to the following reference binary trees:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of numberNodes method:


	public int numberNodes()
	{
		return numberNodes(overallRoot, 0);
	}

	private int numberNodes(IntTreeNode root, int count) 
	{
		if(root == null)
			return count;
				
		count++;
		root.data = count;
		count = numberNodes(root.left, count);
		count = numberNodes(root.right, count);
		
		return count;
	}

0 0

Discussions

Post the discussion to improve the above solution.