排序列表轉換爲二分查找樹
給出一個所有元素以升序排序的單鏈表,將它轉換成一棵高度平衡的二分查找樹
2
1->2->3 => / \
1 3
本題主要考的就是一個平衡二叉樹的生成,但是如果使用常規的插入和調整策略來生成AVL樹會比較麻煩。
/**
* 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* AVL_tree(vector<int> data, int begin, int end)//遞歸生成左右子樹
{
if ((begin > end)||begin<0||end>=data.size())
return NULL;
if (begin == end)
{
TreeNode* rt = (TreeNode*)malloc(sizeof(TreeNode));
rt->val = data[begin];
rt->left = NULL;
rt->right = NULL;
return rt;
}
TreeNode* rt = (TreeNode*)malloc(sizeof(TreeNode));
int now = (begin + end) / 2;
rt->val = data[now];
rt->left = AVL_tree(data, begin, now - 1);
rt->right = AVL_tree(data, now + 1, end);
return rt;
}
TreeNode *sortedListToBST(ListNode *head) {
if (head == NULL)
return NULL;
vector<int> data;
ListNode* p = head;
while (p != NULL)
{
data.push_back(p->val);
p = p->next;
}
TreeNode* rt = (TreeNode*)malloc(sizeof(TreeNode));
int now = data.size() / 2;
rt->val = data[now];
rt->left = (AVL_tree(data, 0, now - 1));//vector左半部分生成左子樹
rt->right = AVL_tree(data, now + 1, data.size() - 1);//vector右半部分生成右子樹
return rt;//返回根節點
}
};