'Difference between returning and not returning in recursion
I have written a program to print the Kth node from root of a binary tree.
// PRINT KTH NODE FROM ROOT (FUNCTION 1)
void printKth(node *root, int k){
if (root == NULL){
return;
}
if (k == 0){
cout<<root -> data<<" ";
return;
}
printKth(root -> left, k-1);
printKth(root -> right, k-1);
}
For the below binary tree, The code prints
// 100
// / \
// 80 120
// / \
// 40 60
//
// OUTPUT - 80 120
The above function works fine until I add a return statement in the second and third last lines.
// PRINT KTH NODE FROM ROOT (FUNCTION 2)
void printKth(node *root, int k){
if (root == NULL){
return;
}
if (k == 0){
cout<<root -> data<<" ";
return;
}
return printKth(root -> left, k-1); // ADDED RETURN STATEMENT
return printKth(root -> right, k-1); // ADDED RETURN STATEMENT
}
For the below binary tree, The code prints
// 100
// / \
// 80 120
// / \
// 40 60
//
// OUTPUT - 80
I can't understand what's happening when adding the return statement.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
