LC.109. 有序链表转换二叉搜索树

思路:中序遍历。

1.转有序数组分治思想。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int>a;
void fun(ListNode* head){
while(head){
a.push_back(head->val);
head=head->next;
}
}
TreeNode* build(int l,int r){
if(l>r) return nullptr;
int mid=(l+r)>>1;
TreeNode* rt=new TreeNode(a[mid]);
rt->left=build(l,mid-1);
rt->right=build(mid+1,r);
return rt;
}
TreeNode* sortedListToBST(ListNode* head) {
fun(head);
return build(0,a.size()-1);
}
};

2.头结点占位分治。

class Solution {
public:
int getLength(ListNode* head) {
int ret = 0;
for (; head != nullptr; ++ret, head = head->next);
return ret;
}

TreeNode* buildTree(ListNode*& head, int left, int right) {
if (left > right) {
return nullptr;
}
int mid = (left + right)>>1;
TreeNode* root = new TreeNode();
root->left = buildTree(head, left, mid - 1);
root->val = head->val;
head = head->next;
root->right = buildTree(head, mid + 1, right);
return root;
}

TreeNode* sortedListToBST(ListNode* head) {
int length = getLength(head);
return buildTree(head, 0, length - 1);
}
};