Here is complete function to print all root to leaf node path comments describe well this function.
static void printLeafNodePathFromRoot(treeNode *rootNode, int path[], int pathLength) { if (rootNode == NULL) //if root node is null return; path[pathLength] = rootNode->val; //add root node value to path array pathLength++; //increase the path length by 1 //if root node is a leaf node then print path from root to that node if (rootNode->leftChild == NULL && rootNode->rightChild == NULL) { //printArray is function which just print the array values printArray(path, pathLength); cout << endl; } //if root node is not leaf node else { //call function for left child if (rootNode->leftChild) tree::printLeafNodePathFromRoot(rootNode->leftChild, path, pathLength); //call function for right child if (rootNode->rightChild) tree::printLeafNodePathFromRoot(rootNode->rightChild, path, pathLength); } }
above mention function is member function of my Tree ADT class you can check complete program here
A Developer
Gy@n!
While the solution works I don’t like that you use a fixed array size to hold the path information. Is there a way that this can be determined dynamically@