码迷,mamicode.com
首页 > 其他好文 > 详细

[leedcode 109] Convert Sorted List to Binary Search Tree

时间:2015-07-21 23:47:06      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

/**
 * 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;
        int len=0;
        ListNode node=head;
        while(node!=null){
            node=node.next;
            len++;
        }
        return getBST(head,0,len-1);
    }
    TreeNode getBST(ListNode head,int start,int end){
        if(start>end) return null;
        int mid=(start+end)/2;
        ListNode temp=head;
        for(int i=start;i<mid;i++){//求中间节点方法————start到mid
            temp=temp.next;
        }
        TreeNode node=new TreeNode(temp.val);
        node.left=getBST(head,start,mid-1);
        node.right=getBST(temp.next,mid+1,end);//注意右侧节点链表的头结点!!!因为和数组求中间节点的方式不一样,链表主要是遍历,求相对位置
        return node;
    }
}

 

[leedcode 109] Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/qiaomu/p/4665969.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!