主要思路
构造平衡的二叉搜索树:首先使用快慢指针法找到中位数,作为根节点,然后递归构造左子树与右子树
#include <iostream>
#include <cstdio>
using namespace std;
#include <queue>
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){}
};
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:
//快慢指针获取中位数
ListNode *getMedian(ListNode *left,ListNode *right) {
ListNode *fast = left;
ListNode *slow = left;
while(fast!=right&&fast->next!=right) {
fast = fast->next;//fast走两步 slow走一步
fast = fast->next;
slow = slow->next;
}
return slow;
}
TreeNode *buildTree(ListNode *left,ListNode *right) {
if(left==right) {
return nullptr;
}
ListNode *mid = getMedian(left,right);
TreeNode *root = new TreeNode(mid->val);
root->left = buildTree(left,mid);
root->right = buildTree(mid->next,right);
return root;
}
TreeNode *sortedListToBST(ListNode *head) {
return buildTree(head,nullptr);
}
};
/**********测试用***********/
ListNode *createList(int a[],int n) {
ListNode *head = nullptr,*p = nullptr;
for(int i = 0;i<n;i++) {
if(head==nullptr) {
head = p = new ListNode(a[i]);
}
else {
p->next = new ListNode(a[i]);
p = p->next;
}
}
return head;
}
void printList(ListNode *h) {
while(h!=nullptr) {
printf("%d -> ",h->val);
h = h->next;
}
printf("null\n");
}
//层次遍历打印bst
void printTree_level_order(TreeNode *root) {
queue<TreeNode *> que;
que.push(root);
while(que.size()>0) {
TreeNode *tn = que.front();
que.pop();
if(tn==nullptr) {
printf("null ");
continue;
}
printf("%d ",tn->val);
que.push(tn->left);
que.push(tn->right);
}
printf("\n");
}
int main() {
int a[] = {-10,-3,0,5,9};
Solution sol;
ListNode *head = createList(a,sizeof(a)/sizeof(int));
printf("list:\n");
printList(head);
printf("BST:\n");
TreeNode *root = sol.sortedListToBST(head);
printTree_level_order(root);
return 0;
}