您的位置:首页 > 其它

[Leetcode]Convert Sorted List to Binary Search Tree

2013-06-28 11:22 627 查看
思路:从链表来建树关键的在于找到中间节点,并且自底向上的来建立。

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