题目:将排好序的链表转化为二叉搜索树
分析:算法思路是取中间为根节点,左边是左子树,右边是右子树,然后递归
答案:
/**
* 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 {
private:
TreeNode* createTree(ListNode* head, int left, int right){
if (left > right)
return NULL;
int mid = (left+right)/2;
// find mid node
ListNode* cNode = head;
for (int i = left; i < mid; i++){
cNode = cNode->next;
}
TreeNode* tNode = new TreeNode(cNode->val);
tNode->left = createTree(head, left,mid-1);
tNode->right = createTree(cNode->next, mid+1, right);
return tNode;
}
int getLength(ListNode* head){
int len = 0;
ListNode* p = head;
while(p){
p = p->next;
len++;
}
return len;
}
public:
TreeNode* sortedListToBST(ListNode* head) {
createTree(head,0,getLength(head)-1);
}
};
注意:很有意思的一个问题是边界的判断。我一开始把最后一句写成createTree(head,0,getLength(head))就出现了无限循环