Solution #1: To store the path, we need an array and an integer to store the length of the path. Here is the recursive algorithm,
void printAllPaths(struct node* root, int *arr, int len) { if(root == NULL) return; arr[len++] = root->data; if((root->left == NULL) && (root->right==NULL)) { int i=0; for(i=0; i < len; i++) printf("%d ", arr[i]); printf("\n"); return; } printAllPaths(root->left, arr, len); printAllPaths(root->right, arr, len); }
5 comments:
Nice Solution!
Nice and simple solution.
Small correction.
10
/ \
11 12
The output will be:
10 11
10 11 12.
That's because after Left-sub-tree is called 10 and 11 will be added to array.
Array becomes |10|11|
10-->11
When Right-sub-tree of 10 is called, the array becomes
|10|11|12|
and hence 10-->11-->12 will be printed .
So reduce the 'len' variable as and when LST is called and finished.
Also reduce only if LST isnt NULL.
DO the same for RST as well .
http://ideone.com/LxXRVk
elegant
Post a Comment