LeetCode OJ:Convert Sorted List to Binary Search Tree

2014-11-24 08:16:01 · 作者: · 浏览: 1

Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.


算法思想:

可以不用定位到中间的节点,只要对链表进行处理就好了,关键步骤在于,head=head->next的处理

/**
 * 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 *BST(ListNode* &head,int start,int end){
        if(start>end)return NULL;
        int mid=(start+end)/2;
        TreeNode *left=BST(head,start,mid-1);
        TreeNode *th=new TreeNode(head->val);
        th->left=left;
        head=head->next;
        th->right=BST(head,mid+1,end);
        return th;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        if(!head)return NULL;
        ListNode *p=head;
        int count=0;
        while(p){count++;p=p->next;}
        return BST(head,0,count-1);
    }
};