LintCode-排序列表轉換為二分查找樹分析及實例
更新時間:2017年04月25日 10:34:10 投稿:lqh
這篇文章主要介紹了LintCode-排序列表轉換為二分查找樹分析及實例的相關資料,需要的朋友可以參考下
給出一個所有元素以升序排序的單鏈表,將它轉換成一棵高度平衡的二分查找樹
您在真實的面試中是否遇到過這個題?
分析:就是一個簡單的遞歸,只是需要有些鏈表的操作而已
代碼:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: a tree node
*/
TreeNode *sortedListToBST(ListNode *head) {
// write your code here
if(head==nullptr)
return nullptr;
int len = 0;
ListNode*temp = head;
while(temp){len++;temp = temp->next;};
if(len==1)
{
return new TreeNode(head->val);
}
else if(len==2)
{
TreeNode*root = new TreeNode(head->val);
root->right = new TreeNode(head->next->val);
return root;
}
else
{
len/=2;
temp = head;
int cnt = 0;
while(cnt<len)
{
temp = temp->next;
cnt++;
}
ListNode*pre = head;
while(pre->next!=temp)
pre = pre->next;
pre->next = nullptr;
TreeNode*root = new TreeNode(temp->val);
root->left = sortedListToBST(head);
root->right = sortedListToBST(temp->next);
return root;
}
}
};
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章:
相關文章
C++ const限定符以及頂層const和底層const的案例詳解
這篇文章主要介紹了C++ const限定符以及頂層const和底層const的案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-09-09
C語言實現(xiàn)通用數據結構之通用集合(HashSet)
這篇文章主要為大家詳細介紹了C語言實現(xiàn)通用數據結構之通用集合,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11

