LintCode-排序列表轉(zhuǎn)換為二分查找樹分析及實例
給出一個所有元素以升序排序的單鏈表,將它轉(zhuǎn)換成一棵高度平衡的二分查找樹
您在真實的面試中是否遇到過這個題?
分析:就是一個簡單的遞歸,只是需要有些鏈表的操作而已
代碼:
/**
* 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++中Socket網(wǎng)絡(luò)編程實例詳解
欄 目:C語言
本文標(biāo)題:LintCode-排序列表轉(zhuǎn)換為二分查找樹分析及實例
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1632.html
您可能感興趣的文章
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排序法函數(shù)
- 01-10深入理解堆排序及其分析
- 01-10深入單鏈表的快速排序詳解
- 01-10內(nèi)部排序之堆排序的實現(xiàn)詳解
- 01-10用c語言實現(xiàn)冒泡排序,選擇排序,快速排序
- 01-10C++實現(xiàn)基數(shù)排序的方法詳解
- 01-10c++ 構(gòu)造函數(shù)的初始化列表
- 01-10歸并排序的遞歸實現(xiàn)與非遞歸實現(xiàn)代碼
- 01-10C++初始化列表學(xué)習(xí)
- 01-10如何使用VC庫函數(shù)中的快速排序函數(shù)


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達(dá)式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機(jī)閱讀
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-10delphi制作wav文件的方法
- 04-02jquery與jsp,用jquery
- 01-10C#中split用法實例總結(jié)


