LeetCode 109. Ordered Linked List Conversion Binary Search Tree (recursive)

Insert picture description here

Ideas:

  • The easiest way is to first store the values ​​in the linked list into a vector in order, and then find the root node of the subtree through a simple dichotomy, and then use recursion to build them all into a tree.

Code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<int> temp;
    TreeNode* build(int l,int r)
    {
    
    
        if(l==r)
        return NULL;
        int mid=l+r>>1;
        TreeNode* root=new TreeNode(temp[mid]);
        root->left=build(l,mid);
        root->right=build(mid+1,r);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
    
    
        ListNode *h=head;
        while(h)
        {
    
    
            temp.push_back(h->val);
            h=h->next;
        }
        return build(0,temp.size());
    }
};

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/108069910