您的位置:首页 > 其它

leetcode 109 Convert Sorted List to Binary Search Tree

2016-06-07 20:28 429 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Subscribe to see which companies asked this question

/**
* 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 *buildTree(ListNode *&head, int left, int right) {
if(left > right) {
return NULL;
}
int mid = left+(right-left+1)/2;
TreeNode *leftNode = buildTree(head, left, mid-1);

TreeNode *root = new TreeNode(head->val);
head = head->next;
root->left = leftNode;

TreeNode *rightNode = buildTree(head, mid+1, right);

root->right=rightNode;
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
TreeNode *root=NULL;
if(head==NULL) return root;

ListNode *l = head;
int cnt = 0;

while(l!=NULL) {
cnt++;
l=l->next;
}

root = buildTree(head, 0, cnt-1);

return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: