Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted linked list: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST: 0 / \ -3 9 / / -10 5
思路:递归。这道题比上一题难度大,是因为链表无法像数组那样按照索引遍历,那么就需要自底向上的回溯,按照中序遍历的顺序,先确定左字树节点,然后确定根节点,最后确定右子树。
/**
* 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 *p=head;
while(p){
len++;
p=p->next;
}
return sortedListToBST(head,0,len-1);
}
TreeNode* sortedListToBST(ListNode* &list,int start,int end){
if(start>end) return NULL;
int mid=(start+end)/2;
TreeNode *left=sortedListToBST(list,start,mid-1);
TreeNode *parent=new TreeNode(list->val);
parent->left=left;
list=list->next;
parent->right=sortedListToBST(list,mid+1,end);
return parent;
}
};