I want to write a function
int Listofleaves (Tree tree,List* list)
which recieve a binary tree -"tree"(the input) and a list pointer "list"(output)...the function supposed to return the trees leaves nodes(nodes with no children) from right to left as a linked list(!) in "list"...and also return at the end the sum of all those leaves....
anyone knows???
thanks for help people
When you just say "List", which kind is it then? Linked List, or just some object?
You have to run through the tree, and then check each of the nodes left node-pointer and right node-pointer. If both is NULL, then the node is a leave-node. While doing that you're taking the value in the leave-node, when finding one, and add it to the sum.
I don't know about the List you were talking about, so I can't say how you're gonna using that one.
I meant linked list the problem ewas to write this code but returning a linked list tat contains the trees leafes from left to right and the function returns their sum as well![]()
To add a node on your linked list, you first have to check the pointer to the start of the list. If this' pointer to the next node is NULL, you set the next-pointer to the new node.
Then you have to set the pointer to the end of the lists next-pointer to the new node, set the next-pointer in the new node to NULL, and then point the whole end-pointer to the new node. Of course, when you want to have the value of the binary trees node too, you have to set that value in the new node of the linked list.
If your linked list doesn't have an end-pointer, but only a start-pointer (which most actually have), then it's a bit harder to implement. You still have to check if the start-pointer is NULL, but if it isn't (it already had been used) you have to go through the whole list, and check if you're at the end. Here's an example:
There's tons of information about this subject, around on the internet.Code:void addNodeAtEnd(node *newNode) { node *temporaryNode = new node; if(startNode == NULL) startNode = newNode; else { temporaryNode = startNode; while(temporaryNode->next != NULL) temporaryNode = temporaryNode->next; temporaryNode->next = newNode; } delete temporaryNode; }
Just make a fast search with some of the many search engines.
Last edited by v0id; 05-03-2007 at 07:42 AM.
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks