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

Convert Sorted List to Binary Search Tree

时间:2015-04-10 21:51:05      阅读:117      评论: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; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private List<TreeNode> list = new ArrayList<TreeNode>();
    
    public TreeNode creatBST(int low,int high) {
        if(low<=high) {
            int mid = (high+low)/2;
            TreeNode root = list.get(mid);
            root.left = creatBST(low,mid-1);
            root.right = creatBST(mid+1,high);
            return root;
        }
        else return null;
      
    }
    
    public TreeNode sortedListToBST(ListNode head) {
        while(head!=null) {
            TreeNode node = new TreeNode(head.val);
            list.add(node);
            head = head.next;
        }
        return creatBST(0,list.size()-1);

    }
}

 

Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4415692.html

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