Reputation: 5
I need to find the longest ROOT to LEAF path in a tree. I already have code to find the shortest root to leaf and I was wondering if I could reuse it in any way to find the longest path.
// Recursive function used by leftMostShortest
// to print the first shortest root to leaf path
void AlberoCircuito::printPath(string Data, unordered_map<string,
string> parent)
{
// If the root's data is same as
// its parent data then return
if (parent[Data] == Data)
return;
// Recur for the function printPath
printPath(parent[Data], parent);
// Print the parent node's data
pathMinimo.push_back(parent[Data]);
}
// Function to perform level order traversal
// until we find the first leaf node
vector<string> AlberoCircuito::leftMostShortest(NodoAlbero* root)
{
// Queue to store the nodes
queue<NodoAlbero*> q;
// Push the root node
q.push(root);
// Initialize the value of first
// leaf node to occur as -1
string LeafData = " ";
// To store the current node
NodoAlbero* temp = NULL;
// Map to store the parent node's data
unordered_map<string, string> parent;
// Parent of root data is set as it's
// own value
parent[root->value] = root->value;
// We store first node of the smallest level
while (!q.empty()) {
temp = q.front();
q.pop();
// If the first leaf node has been found
// set the flag variable as 1
if (!temp->leftPtr && !temp->rightPtr) {
LeafData = temp->value;
break;
}
else {
// If current node has left
// child, push in the queue
if (temp->leftPtr) {
q.push(temp->leftPtr);
// Set temp's left node's parent as temp
parent[temp->leftPtr->value] = temp->value;
}
// If current node has right
// child, push in the queue
if (temp->rightPtr) {
q.push(temp->rightPtr);
// Set temp's right node's parent
// as temp
parent[temp->rightPtr->value] = temp->value;
}
}
}
// Recursive function to print the first
// shortest root to leaf path
printPath(LeafData, parent);
// Print the leaf node of the first
// shortest path
pathMinimo.push_back(LeafData);
return pathMinimo;
}
So this is the code I'm using to find the shortest path and store it in a vector. These are members of a class.
Is there any way to just modify it and reuse it? Or do you think I have to start over? Thanks :)
Upvotes: 0
Views: 585