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

LeetCode Convert Sorted List to Binary Search Tree

时间:2015-05-06 13:19:54      阅读:85      评论: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 {
    private static ListNode currentHead = null;  
	
    private TreeNode buildTree(int start, int end) {  
        if (start > end) 
            return null;  
        
        int mid = start + end >> 1;  
        TreeNode left = buildTree(start, mid-1);  
        TreeNode root = new TreeNode(currentHead.val);   
        root.left = left;  
        currentHead = currentHead.next;  
        root.right = buildTree(mid + 1, end);  
        return root;  
    }  
      
    public TreeNode sortedListToBST(ListNode head) {  
        if(head == null)
            return null;  
          
        currentHead = head;  
        int n = 0;  
        while (head != null) {  
            n++;  
            head = head.next;  
        }  
          
        return buildTree(0, n-1);  
    }  
}



LeetCode Convert Sorted List to Binary Search Tree

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45533471

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