LintCode-排序列表轉(zhuǎn)換為二分查找樹分析及實(shí)例
給出一個(gè)所有元素以升序排序的單鏈表,將它轉(zhuǎn)換成一棵高度平衡的二分查找樹
您在真實(shí)的面試中是否遇到過這個(gè)題?
分析:就是一個(gè)簡單的遞歸,只是需要有些鏈表的操作而已
代碼:
/** * 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; } } };
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C++ const限定符以及頂層const和底層const的案例詳解
這篇文章主要介紹了C++ const限定符以及頂層const和底層const的案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09C++編程中使用設(shè)計(jì)模式中的policy策略模式的實(shí)例講解
這篇文章主要介紹了C++編程中使用設(shè)計(jì)模式中的policy策略模式的實(shí)例講解,文章最后對策略模式的優(yōu)缺點(diǎn)有一個(gè)簡單的總結(jié),需要的朋友可以參考下2016-03-03C語言實(shí)現(xiàn)通用數(shù)據(jù)結(jié)構(gòu)之通用集合(HashSet)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)通用數(shù)據(jù)結(jié)構(gòu)之通用集合,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11好用的C++ string Format“函數(shù)”介紹
大家好,本篇文章主要講的是好用的C++ string Format“函數(shù)”介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽2021-12-12C++類中const修飾的成員函數(shù)及日期類小練習(xí)
將const修飾的“成員函數(shù)”稱之為const成員函數(shù),const修飾類成員函數(shù),表明在該成員函數(shù)中不能對類的任何成員進(jìn)行修改,下面這篇文章主要給大家介紹了關(guān)于C++類中const修飾的成員函數(shù)及日期類小練習(xí)?的相關(guān)資料,需要的朋友可以參考下2023-01-01深入分析C語言中結(jié)構(gòu)體指針的定義與引用詳解
本篇文章是對C語言中結(jié)構(gòu)體指針的定義與引用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05