[LeetCode] Convert Sorted List to Binary Search Tree



/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    TreeNode *helper(ListNode *&head, int start, int end)
    {
        //base case:
        if(start > end || head==NULL)
            return NULL;
        
        //recursive step: build left subtree, root and right subtree
        int median=(start+end)/2;
        TreeNode *left=helper(head,start,median-1);
        TreeNode *root=new TreeNode(head->val);
        root->left=left;
        head=head->next;
        TreeNode *right=helper(head,median+1,end);
        root->right=right;
        
        return root;
    }

    TreeNode *sortedListToBST(ListNode *head) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int n=0;
        ListNode *p=head;
        while(p!=NULL){
            p=p->next;
            n++;
        }
        return  helper(head,0,n-1);
    }
};


發佈了110 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章