Skip to main content
GameDev.net gamedev.net
🔒 Locked

a Binary Tree problem......

Started by nabeelisnabeel Jan 31, 2006 at 11:15 PM 5 replies 800+ views
Original Post
nabeelisnabeel
nabeelisnabeel
hi guys I have to write a function get_level_with_maximum_no_of_nodes(); I think the name is self-explanatory. I m using a Linked represenatation of binary tree. I guess this function has somethign to do with Level Order Printing of binary tree , which uses a queue? mm not sure, jhust a guess. any pointers fomr ur side dudes?
Endar
Endar
Someone correct me if I'm wrong, but I have a feeling that the only way you'll be able to do this is traverse the whole tree and keep track of how many nodes on each level using an array or something.
[size="2"][size=2]Mort, Duke of Sto Helit: NON TIMETIS MESSOR -- Don't Fear The Reaper
eleusive
eleusive
You might as well just have an array representing how many nodes are at each level, and increment/decrement array whenever you insert/remove a new element onto level i. Then, you could just have a variable that contains the index of the level with the most number of nodes, and update that as you insert/remove elements.
"What are you trying to tell me? That I can write an O(N^2) recursive solution for a 2-dimensional knapsack?" "No, programmer. I'm trying to tell you that when you're ready, you won't have to." -Adapted from "The Matrix"
_goat
_goat
Node * getNodeWithMaximumChildren(Node * top_of_branch){	if (countNodes(top_of_branch->left_node) >= countNodes(top_of_branch->right_node))		return top_of_branch->left_node;	else		return top_of_branch->right_node;}unsigned long countNodes(Node * node){	unsigned long left_count = 0, right_count = 0;		if (node->left_node) left_count = countNodes(node->left_node);	if (node->right_node) right_count = countNodes(node->right_node);		return left_count + right_count;}


(Edit: Written because it's been a while since I wrote a recursive function)
jpetrie
jpetrie
_goat, your countNodes fails to account for node you are currently looking at. It will always return zero.
nabeelisnabeel
nabeelisnabeel
Thanx for all of you 4 ur help.
I will apply your code and see hat works.
discman1028
discman1028
Quote:
Please notice that the code above is not re-entrant (and hence e.g. not thread save). It would be better to allocate the array outside and to pass it into the function. The solution above need not be a problem but may become one in the future, so I wanted it to be mentioned so that nabeelisnabeel is aware of.


Can you elaborate on what re-entrant and not thread safe means?

(http://www.gamedev.net/community/forums/topic.asp?topic_id=372915)


Thanks.
--== discman1028 ==--

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.