Created
March 18, 2016 19:01
-
-
Save zhhailon/45e15383bc6e407fb86c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
2 Given a binary tree, print out all of its root-to-leaf | |
3 paths, one per line. Uses a recursive helper to do the work. | |
4 */ | |
void printPaths(struct node* node) { | |
int path[1000]; | |
printPathsRecur(node, path, 0); | |
} | |
/* | |
Recursive helper function -- given a node, and an array containing | |
the path from the root node up to but not including this node, | |
print out all the root-leaf paths. | |
*/ | |
void printPathsRecur(struct node* node, int path[], int pathLen) { | |
if (node==NULL) | |
return; | |
// append this node to the path array | |
path[pathLen] = node->data; | |
pathLen++; | |
// it's a leaf, so print the path that led to here | |
if (node->left==NULL && node->right==NULL) { | |
printArray(path, pathLen); | |
} | |
else { | |
// otherwise try both subtrees | |
printPathsRecur(node->left, path, pathLen); | |
printPathsRecur(node->right, path, pathLen); | |
} | |
} | |
/* | |
Utility that prints out an array on a line. | |
*/ | |
void printArray(int ints[], int len) { | |
int i; | |
for (i=0; i<len; i++) { | |
printf("%d ", ints[i]); | |
} | |
printf("\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment