Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST
思路:已经是sorted list并且按升序排列,那么和in-order traversal的顺序是一致的,所以采用类似in-order的顺序来构建
麻烦的点是recursion,好难理解。。。另外就是reference data type的处理
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; next = null; }
* }
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode p;
public TreeNode sortedListToBST(ListNode head) {
if (head == null) return null;
p = head;
ListNode run = head;
int len = 0;
while(run!=null){
run = run.next;
len++;
}
return sortedListToBST(0,len-1);
}
public TreeNode sortedListToBST(int left, int right){
if(left>right) return null;
int mid = (left+right)/2;
// ListNode q =p;
TreeNode leftC = sortedListToBST(left, mid-1);
TreeNode parent = new TreeNode(p.val);
parent.left = leftC;
p=p.next;
TreeNode rightC = sortedListToBST(mid+1, right);
parent.right = rightC;
return parent;
}
}