您的位置:首页 > 其它

【LeetCode】Convert Sorted List to Binary Search Tree

2015-03-28 23:55 453 查看
题目:Convert Sorted List to Binary Search Tree

<span style="font-size:18px;">/**LeetCode convert link-list to Binary Search Tree
*题意:给定一个按照升序排列的链表,要求将其转化为一个高度平衡的二查搜索树
*思路:因为链表是升序排列的,所以转化为二叉搜索树是简单的,但是要求是平衡的,即左右子数的高度 差在1之内
*可以取中间的点为根节点,保证两边数量是一样的,这样递归下来就能得到平衡的二叉树
* 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; }
* }
*/
package javaTrain;

public class Train19 {
public TreeNode sortedListToBST(ListNode head) {
if(head == null) return null;
ListNode pre = head; //用于找到中间的节点
ListNode last = head;
TreeNode root;;
if(head.next == null){
root = new TreeNode(head.val);
root.left = null;
root.right = null;
return root;
}
while(pre != null && pre.next != null){ //找到中间节点
pre = pre.next.next;
last = last.next;
}
root = new TreeNode(last.val);
ListNode newHead = last.next;
last.next = null;
root.left = sortedListToBST(head);
root.right = sortedListToBST(newHead);
return root;
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  BST 链表 leetcode