Reputation: 3
I have this fucntion that converts a Binary Tree to a Linked List. I am failing to understand how recursion works here since the flatten_helper function returns void. So what actually happens when a recursion function returns void? Can someone help me understand what happens in the code here?
Also, any links to understand recursion in tree problems would be highly appreciated as I am struggling to get a grasp on these types of problems.
void flatten_helper(struct TreeNode* root, struct TreeNode** prev)
{
if (root == NULL) return;
flatten_helper(root->right, prev);
flatten_helper(root->left, prev);
root->right = *prev;
root->left = NULL;
*prev = root;
}
void flatten(struct TreeNode* root)
{
struct TreeNode **prev;
prev = (struct TreeNode *)malloc(sizeof(struct TreeNode *));
*prev = NULL;
flatten_helper(root, prev);
*prev = NULL;
free(prev);
}
Code Credits - Leetcode
Upvotes: 0
Views: 74
Reputation: 1301
Don't think of flatten_helper() as a function, think of it as a procedure. It doesn't return a value, it actually does some work (it sets root->right to *prev, root->left to NULL, and *prev to root).
Upvotes: 1