https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/
这道题用递归很简单,每次把中间结点找到,中间结点是root,然后递归左半部份,建左子树,递归右半部份,建右子树。
找中间结点的算法就是two pointer的方法,一个每次前进一步,一个每次前进两步,知道到达tail为止。注意每次循环都需要检查 p2!=tail p2.next!=tail, 因为p2每次前进两步,如果只检查p2 != tail,可能把tail跳过了。
注意,当只有两个节点的时候,是没有左子树的,需要注意这种情况。
public class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head==null) return null;
if(head.next==null){
TreeNode root = new TreeNode(head.val);
return root;
}
ListNode tail = head;
while(tail.next!=null){
tail = tail.next;
}
TreeNode root = getTree(head, tail);
return root;
}
public TreeNode getTree(ListNode head, ListNode tail){
if(head==tail){
TreeNode root = new TreeNode(head.val);
return root;
}
if(head==null||tail==null) return null;
ListNode p1 = head;
ListNode p2 = head;
ListNode pre = head;
while(p2 != tail && p2.next!=tail){
pre = p1;
p1 = p1.next;
p2 = p2.next.next;
}
TreeNode root = new TreeNode(p1.val);
if(head!=p1) root.left = getTree(head, pre);
root.right = getTree(p1.next, tail);
return root;
}
}
http://blog.youkuaiyun.com/fightforyourdream/article/details/16940205
这里的方法是用一边开的区间来避免找tail node和不需要保留pre指针。