0

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

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.