您的位置:首页 > 其它

Convert Sorted List to Binary Search Tree 把有序链表转为BST@LeetCode

2013-11-25 10:27 501 查看
万能的递归法,注意到有一点比较巧的是,由于单链表都是单向的。所以这里我的查找区间设置为左闭右开!这样就避免了去找mid节点的前一个节点

package Level4;

import Utility.ListNode;
import Utility.TreeNode;

/**
* Convert Sorted List to Binary Search Tree
*
* Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
*
*/
public class S109 {

public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode n2 = new ListNode(3);
head.next = n2;
TreeNode root = sortedListToBST(head);
}

public static TreeNode sortedListToBST(ListNode head) {
return rec(head, null);
}

// 在区间[start, end)里递归,后面的end是包括在内的,这样可以避免要多用一个指针来记录mid前的节点
public static TreeNode rec(ListNode start, ListNode end){
if(start == end){
return null;
}

// 一次遍历找到中点的方法:快慢指针
ListNode mid = start; // 该指针最终会指向中点
ListNode probe = start; // 探针最终会到达end
while(probe!=end && probe.next!=end){ // 探针完成搜索,注意停止条件是和end比较而不是和null比!
mid = mid.next;
probe = probe.next.next;
}

TreeNode root = new TreeNode(mid.val);
root.left = rec(start, mid);
root.right = rec(mid.next, end);
return root;
}

}


/**
* 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 {
public TreeNode sortedListToBST(ListNode head) {
return rec(head, null);
}

public TreeNode rec(ListNode start, ListNode end) {
if(start == end) {
return null;
}
ListNode p = start, q = start;
while(q != end && q.next != end) {
p = p.next;
q = q.next.next;
}

TreeNode root = new TreeNode(p.val);
root.left = rec(start, p);
root.right = rec(p.next, end);

return root;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐