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

LeetCode——Convert Sorted List to Binary Search Tree

时间:2016-04-15 21:41:22      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

原题链接:https://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/

题目:给定一个有正序链表,将其转换成一个二叉搜索树。

思路:能够依照之前的数组的思路来做。即找到中间值。再左右递归建树。

	public TreeNode sortedListToBST(ListNode head) {
		if (head == null)
			return null;
		int len = 0;
		ListNode tmp = head;
		while (tmp != null) {
			tmp = tmp.next;
			len++;
		}
		return sortedListToBST(head, len);
	}

	public TreeNode sortedListToBST(ListNode head, int len) {
		if (len <= 0)
			return null;
		int mid = (1 + len) / 2;
		ListNode p = head;
		int tmp = mid - 1;
		while (tmp > 0) {
			p = p.next;
			tmp--;
		}
		TreeNode root = new TreeNode(p.val);
		root.left = sortedListToBST(head, mid - 1);
		root.right = sortedListToBST(p.next, len - mid);
		return root;
	}
	// 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;
		}
	}


LeetCode——Convert Sorted List to Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/lcchuguo/p/5396739.html

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