您的位置:首页 > 其它

[LeetCode]Convert Sorted List to Binary Search Tree

2013-05-28 12:07 323 查看
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
//We create nodes bottom-up, and assign them to its parents.
//The bottom-up approach enables us to access the list in its order while creating nodes.
public:
//note: because we use the method bottom to up, so the change of head must be along the way down
//when back to current level, the head is in the right place
TreeNode* Convert2BST(ListNode*& head, int start, int end)
{
if(start > end)
return NULL;
int mid = (start+end)/2;
TreeNode* left = Convert2BST(head, start, mid-1);
TreeNode* parent = new TreeNode(head->val);//bottom-up, so the assign should be put here
parent->left = left;
head = head->next;//one valid element is visited, so should point to next, because of bottom-up
parent->right = Convert2BST(head, mid+1, end);
return parent;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = 0;
ListNode* p = head;
while(p)
{
n++;
p = p->next;
}
//then divide and conquer
return Convert2BST(head, 0, n-1);
}
};

second time

/**
* 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* sortedListToBSTUtil(ListNode*& cur, int start, int end)
{
if(start > end) return NULL;
int mid = start+(end-start)/2;
TreeNode* left = sortedListToBSTUtil(cur, start, mid-1);
TreeNode* root = new TreeNode(cur->val);
cur = cur->next;
TreeNode* right = sortedListToBSTUtil(cur, mid+1, end);
root->left = left;
root->right = right;
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int cnt = 0;
ListNode* p = head;
while(p != NULL) p = p->next, cnt++;
return sortedListToBSTUtil(head, 0, cnt-1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: