Hi all;
The matrix paths[i][j] determine the path index i meeting the node number j.
I have written the following code for traversing all of the paths in a binary tree. There is no problem in debugging but as trace line by line, there is a problem in running the code which "counterpath" is not increased it is remain 0. Therefore the matrix Paths is overwritten in rows. The path number 1,2, ... is written in path number 0 when they are founded.
Would you please give me some guidance that what is the problem of my code?
tree nodes rows are nodes and columns are: 0:leaf/split node, 1: left node, 2&3 are not important now, 4: right node
for instance TREENODES[21][0]=1 means that this is leaf node, TREENODES[21][1]=40 means than the left child of 21 is 40, TREENODES[21][4]=45 means than the right child of 21 is 45.
I want to find all of the paths from this arrays and save them in a matrix named Paths. Each row of it determines a path and each column of it determine the meeting node of path. For instance Paths[2]={0,1,5,11,27,50,94} means that for the third leaf from the left (node:94) there is a path traversing the node numbers 0,1,5,11,27,50,94
All of variable such as counterpath,counterelempath, Paths,.. are global variables
void findpath(int node, int counterpath, int counterelempath)
{
if(numvisitedleaves==numofleaves)
return;
Paths[counterpath][counterelempath]=node;
if((TREENODES[node][4]==MAXNUMINFI) && (TREENODES[node][1]==MAXNUMINFI))
{
addpath(counterelempath);
++counterpath;// one path=one leaf is found go to next leaf=path
++numvisitedleaves;
}
else
{
++counterelempath;
findpath(TREENODES[node][1],counterpath,counterelempath);
findpath(TREENODES[node][4],counterpath,counterelempath);
}
}
void main()
{
counterpath=0;
node=0;
counterelempath=0;
numvisitedleaves=0;
while(numvisitedleaves!=numofleaves)
findpath(node,counterpath,counterelempath); // find all paths from this node. At first this node is root=0 and index of it is 0
}
Your code is incomplete. We can not compile and run it.
I don't understand what you are trying to do. ¿What's the purpose of the `Paths' matrix? If you want the path to the root, an array would suffice.
You are using global variables instead of simply arguments to the function. That makes the code hard to follow and error prone (especially considering that you are using recursion)
`node' is supposed to represent the current node that you are working on. However, if it has a left child you change it in node=TREENODES[counterelempath][1];. And later in `findpath()'.
So later, when you test if it has a right child, you lost any reference to the "current" node.
++counterpath;// one path=one leaf is found go to next leaf=path
++numvisitedleaves;
}
else
{
++counterelempath;
findpath(TREENODES[node][1], int counterpath, int counterelempath);
findpath(TREENODES[node][4], int counterpath, int counterelempath);
}
}