#include <iostream>
using namespace std;
/*
题目要求:
Given a singly linked list where elements are
sorted in ascending order, convert it to a height
balanced BST.
这道题可以与108的根据有序数组构建平衡二叉搜索树作对比,由于有序数组可以
随机访问元素,所以108那道题可以用自顶向下的方法构建树。但是单链表不能随机
访问,只能顺序访问,根据这个数据结构的特点,自顶向下的建树顺序不太妥当,应当
用自底向上的建树顺序,从左向右扫描链表,由于比中间数字小的数字都是该数字的左子树,
所以可以先构建所有可能的右子树,然后构建中间数字的节点,再考虑其右子树。
*/
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/**
* Definition for a binary tree node.
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* sortedListToBST(ListNode* head) {
int len = 0;
ListNode* cur = head;
while (cur) {
cur = cur->next;
len++;
}
return bottomUp(head, 0, len - 1);
}
private:
//注意要用引用参数
TreeNode* bottomUp(ListNode* &h, int left, int right){
//如果链表为空,则返回空指针
if (!h) {
return NULL;
}
if (left > right) {
return NULL;
}
int mid = (left + right) / 2;
//构建左子树
TreeNode* lChild = bottomUp(h, left, mid - 1);
//当前节点
TreeNode* current = new TreeNode(h->val);
current->left = lChild;
h = h->next;
//构建右子树
TreeNode* rChild = bottomUp(h, mid + 1, right);
current->right = rChild;
return current;
}
};
int main(int argc, const char * argv[]) {
ListNode one(1);
ListNode two(2);
ListNode three(3);
one.next = &two;
two.next = &three;
Solution s;
TreeNode *res = s.sortedListToBST(&one);
return 0;
}