Function to print all root to leaf node path of a binary tree

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!

About Gyaneshwar Pardhi

Exploring the world and trying to know how can i involve to make this perfect. Gy@n!
This entry was posted in c++, Data Structure, interview Question, Programming and tagged , . Bookmark the permalink.

1 Response to Function to print all root to leaf node path of a binary tree

  1. Amit says:

    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@

Leave a comment