LeetCode109 Convert Sorted List to Binary Search Tree

详细见:leetcode.com/problems/convert-sorted-list-to-binary-search-tree


Java Solution: github

package leetcode;

import java.util.ArrayList;
import java.util.HashMap;

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

import tools.ListNode辅助.ListNode;
import tools.TreeNode辅助.TreeNode;

public class P109_ConvertSortedListtoBinarySearchTree {
	public static void main(String[] args) {
		ListNode head = tools.ListNode辅助.A_一维生成器(new int[] {1, 2, 3});
		TreeNode root = new Solution2().sortedListToBST(head);
		tools.TreeNode辅助.B_按层打印(root);
	}
	/*
	 * 	TLE了,对时间的要求很高哪。
	 */
	static class Solution {
	    public TreeNode sortedListToBST(ListNode head) {
	    	int len = 0;
	    	ListNode cur = head;
	    	while (cur != null) {
	    		len ++;
	    		cur = cur.next;
	    	}
	    	int[] nums = new int[len];
	    	len = 0;
	    	cur = head;
	    	while (cur != null) {
	    		nums[len] = cur.val;
	    		len ++;
	    		cur = cur.next;
	    	}
	        return sortedArrayToBST(nums, 0, len - 1);
	    }
		private TreeNode sortedArrayToBST(int[] nums, int i, int j) {
			if (i > j) {
				return null;
			}
			if (i == j) {
				return new TreeNode(nums[i]);
			}
			int root_index = (i + j) / 2;
			TreeNode root = new TreeNode(nums[root_index]);
			root.left = sortedArrayToBST(nums, i, root_index - 1);
			root.right = sortedArrayToBST(nums, root_index + 1, j);
			return root;
		}
	}
	/*
	 * 	还是TLE,是不是rehash的锅
	 * 	下一个方法采用ArrayList的吧
	 */
	static class Solution2 {
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
	    public TreeNode sortedListToBST(ListNode head) {
	    	int count = 0;
	    	while (head != null) {
	    		map.put(count ++, head.val);
	    		head = head.next;
	    	}
	    	return zxwtry_generate(0, count - 1);
	    }
		private TreeNode zxwtry_generate(int i, int j) {
			if (i > j) {
				return null;
			}
			if (i == j) {
				return new TreeNode(map.get(i));
			}
			int mid = (i + j) / 2;
			TreeNode root = new TreeNode(map.get(mid));
			root.left = zxwtry_generate(i, mid - 1);
			root.right = zxwtry_generate(mid + 1, j);
			return root;
		}
	}
	/*
	 * 	艰难地AC了
	 * 	3 ms
	 */
	static class Solution3 {
		ArrayList<Integer> arr = new ArrayList<>();
	    public TreeNode sortedListToBST(ListNode head) {
	    	while (head != null) {
	    		arr.add(head.val);
	    		head = head.next;
	    	}
	    	return sortedArrayToBST(0, arr.size() - 1);
	    }
	    private TreeNode sortedArrayToBST(int i, int j) {
			if (i > j) {
				return null;
			}
			if (i == j) {
				return new TreeNode(arr.get(i));
			}
			int root_index = (i + j) / 2;
			TreeNode root = new TreeNode(arr.get(root_index));
			root.left = sortedArrayToBST(i, root_index - 1);
			root.right = sortedArrayToBST(root_index + 1, j);
			return root;
		}
	}
}


C Solution: github

/*
*/

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    int val;
    struct ListNode *next;
};


struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

typedef struct ListNode sln;
typedef struct ListNode * pln;
typedef struct TreeNode stn;
typedef struct TreeNode * ptn;

ptn search(int* a, int ai, int aj) {
    int am = (ai + aj + 1) / 2;
    ptn n = NULL;
    if (ai > aj) return NULL;
    n = (ptn) malloc(sizeof(stn));
    n->left = search(a, ai, am-1);
    n->right = search(a, am+1, aj);
    n->val = a[am];
    return n;
}

ptn sortedListToBST(pln h) {
    int hn = 0, *a = NULL, i = 0;
    pln t = h;
    ptn ans = NULL;
    while (t != NULL) {
        t = t->next;
        hn ++;
    }
    a = (int*) malloc(sizeof(int) * hn);
    t = h;
    while (t != NULL) {
        a[i] = t->val;
        t = t->next;
        i ++;
    }
    ans = search(a, 0, hn-1);
    free(a);
    return ans;
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/convert-sorted-list-to-binary-search-tree
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月29日
    @details:    Solution: 256ms 86.37%
'''

class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def search(self, n, ni, nj):
        if ni > nj: return None
        nm = (ni+nj) // 2
        root = TreeNode(n[nm])
        root.left = self.search(n, ni, nm-1)
        root.right = self.search(n, nm+1, nj)
        return root
    
    def sortedListToBST(self, h):
        """
        :type h: ListNode
        :rtype: TreeNode
        """
        n, l = h, []
        while n != None: 
            l.append(n.val)
            n = n.next
        return self.search(l, 0, len(l)-1)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值