您的位置:首页 > 其它

LeetCode Convert Sorted List to Binary Search Tree

2014-08-16 23:35 344 查看
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

思路:

可以先将 链表 转换成 数组,然后直接使用 数组那题的代码。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:

TreeNode *sortedListToBST(ListNode *head) {
vector<int> ivec;
while (head) {
ivec.push_back(head->val);
head = head->next;
}
return sortedArrayToBST(ivec);
}

TreeNode *sortedArrayToBST(vector<int> &num) {
int n = num.size();
if (n == 0)
return NULL;
TreeNode *head = new TreeNode(num[(n - 1) / 2]);
if (n - 3 < 0)
head->left = NULL;
else
head->left = creatBST(num, 0, (n - 3) / 2);
head->right = creatBST(num, (n + 1) / 2, n - 1);
return head;
}

TreeNode *creatBST(vector<int> &num, int left, int right) {
if (right < left)
return NULL;
int mid = (left + right) / 2;
TreeNode *myNode = new TreeNode(num[mid]);
myNode->left = creatBST(num, left, mid - 1);
myNode->right = creatBST(num, mid + 1, right);
return myNode;
}
};


直接使用链表转化,代码更少。

class Solution {
public:
TreeNode *sortedListToBST(ListNode *head) {
if (head == NULL)
return NULL;

ListNode *pslow = head, *pa = head, *pb = head->next;
while (pb != NULL && pb->next != NULL) {
pslow = pa;
pa = pa->next;
pb = pb->next->next;
}

TreeNode *root = new TreeNode(pa->val);
pb = pa->next;
pslow->next = NULL;
if (pa != head)
root->left = sortedListToBST(head);
root->right = sortedListToBST(pb);

return root;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 二叉树 链表