排序列表中的两个递归函数语句到BST代码

因为我是编程新手,所以我正在解决LeetCode上的问题,并尝试对二进制搜索树进行排序列表。这是GeeksforGeeks代码,因为我做不到,一直在寻找解决方案。有人可以向我解释此代码中的递归流程以及此代码如何工作吗?

class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {

    ListNode* h = head;
    ListNode* t = head;
    //TreeNode* root = new TreeNode;
    int count = 0;
    int c=0;

    while(h!=NULL)
    {
        count++;
        h=h->next;
    }

    return sortListToBST(&head,count);

}

TreeNode* sortListToBST(ListNode** head_ref, int n)
{

if (n <= 0)  
    return NULL;  


TreeNode* sortlist = sortListToBST(head_ref, n/2); 
TreeNode* root = new TreeNode((*head_ref)->val);    
root->left = sortlist; 

*head_ref = (*head_ref)->next;  

root->right = sortListToBST(head_ref, n - n / 2 - 1);       
return root;

}



};
评论