您的位置:首页 > 其它

leetcode---Convert Sorted List to Binary Search Tree---二叉搜索树

2016-09-20 20:38 417 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

/**
* 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:
TreeNode* make(ListNode* head, int low, int high)
{
if(low > high)
return NULL;

int mid = (low + high) / 2;
ListNode *p = head;
for(int i=low; i <mid; i++)
{
p = p->next;
}
TreeNode *root = new TreeNode(p->val);
root->left = make(head, low, mid-1);
root->right = make(p->next, mid+1, high);
return root;
}

TreeNode* sortedListToBST(ListNode* head)
{
int n = 0;
ListNode *p = head;
while(p)
{
n++;
p = p->next;
}
return make(head, 0, n-1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: