排序列表转换为二分查找树
给出一个所有元素以升序排序的单链表,将它转换成一棵高度平衡的二分查找树
样例
2
1->2->3 => / \
1 3
主要思想:
本题主要考的就是一个平衡二叉树的生成,但是如果使用常规的插入和调整策略来生成AVL树会比较麻烦。
本题主要考的就是一个平衡二叉树的生成,但是如果使用常规的插入和调整策略来生成AVL树会比较麻烦。
这里因为给定的就是一个排序好的链表所以只需要递归的生成左右子树就很方便了。
所以使用一个vector来存储链表的值,便于随机访问,然后
正中间的数作为根节点,然后递归的将vector的左半部分生成左子树,右半部分生成右子树。
/**
* 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;//返回根节点
}
};