题目:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析:
建树,肯定是借助递归!!
先使用第一个节点;
先建左子树,然后赋给root的左指针;这里的巧妙之处在于建立左子树的时候顺便把下一个节点(下一个root)加入到列表中;
然后用上一次加入到列表中的节点作为root;而且再次加入新的节点到列表中,调用建树函数建立右子树
参考代码:
http://blog.csdn.net/linhuanmars/article/details/24613781
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null)
return null;
ListNode cur = head;
int count = 0;
while(cur!=null)
{
cur = cur.next;
count++;
}
ArrayList<ListNode> list = new ArrayList<ListNode>();
list.add(head);
return helper(list,0,count-1);
}
private TreeNode helper(ArrayList<ListNode> list, int l, int r)
{
if(l>r)
return null;
int m = (l+r)/2;
TreeNode left = helper(list,l,m-1);
TreeNode root = new TreeNode(list.get(0).val);
root.left = left;
list.set(0,list.get(0).next);
root.right = helper(list,m+1,r);
return root;
}
}