LeetCode Convert Sorted List to Binary Search Tree

原创 2015年07月07日 08:32:14

Description:

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

Solution:

每次dfs记录开通和结束的节点下标,从而计算出他的长度。根据长度进行构造,和前面几道题目一样,算出中心位置的下标,取出val作为子节点。再往下递归。

import java.util.*;

public class Solution {
	public TreeNode sortedListToBST(ListNode head) {
		int len = 0;
		ListNode temp = head;
		while (temp != null) {
			len++;
			temp = temp.next;
		}
		return dfs(head, 0, len - 1);
	}

	TreeNode dfs(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++)
			temp = temp.next;
		TreeNode root = new TreeNode(temp.val);
		root.left = dfs(head, start, mid - 1);
		root.right = dfs(temp.next, mid + 1, end);

		return root;
	}
}


[Leetcode] Convert Sorted List to Binary Search Tree Solution

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

LeetCode-Convert Sorted List to Binary Search Tree

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode...

【Leetcode】Two Problems: Convert Sorted Array/List to Binary Search Tree

First let's try easier one: Given an array where elements are sorted in ascending order, convert it...

leetcode-109-Convert Sorted List to Binary Search Tree

#include using namespace std; /* 题目要求: Given a singly linked list where elements are sorted in ...

Convert Sorted List to Binary Search Tree -- LeetCode

原题链接: http://oj.leetcode.com/problems/convert-sorted-list-to-binary-search-tree/  这个题是二分查找树的题目,要把一个有...

LeetCode - 109. Convert Sorted List to Binary Search Tree

同样是构建平衡的BST,这道题目的思路与上一题是一样的,都是通过递归调用的方式逐步找到每一个子树的root,然后添加左子树和右子树。因为这里数字的载体由array变成了linked list,所以也变...

Convert Sorted List to Binary Search Tree - LeetCode 109

题目描述: Given a singly linked list where elements are sorted in ascending order, convert it to a heig...
  • bu_min
  • bu_min
  • 2015年06月10日 21:07
  • 255

[Leetcode]Convert Sorted List to Binary Search Tree

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

【leetcode】Convert Sorted Array/List to Binary Search Tree

ProblemCodeSolution1/* * Dynamic programming,divide problem as two smaller */ struct TreeNode* so...
  • yzt33
  • yzt33
  • 2015年06月30日 13:05
  • 383

leetcode__Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree  Total Accepted: 12283 Total Submissions: 45910My Submiss...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Convert Sorted List to Binary Search Tree
举报原因:
原因补充:

(最多只允许输入30个字)