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

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

LeetCode Convert Sorted List to Binary Search Tree 解题报告

从给定的有序链表生成一颗平衡二叉树。 解题思路:最容易想到的就是利用数组生成二叉树的方法,找到中间节点作为二叉树的root节点,然后分别对左右链表递归调用分别生成左子树和右子树。时间复杂度O(N*lg...

LeetCode 108, 109. Convert Sorted Array/List to Binary Search Tree

1. 题目描述 Given an array where elements are sorted in ascending order, convert it to a height bal...

Convert Sorted List to Binary Search Tree(leetcode)

题目:

leetcode_108 Convert Sorted List to Binary Search Tree

题目分析: 给定一个升序的单链表,将其转换为一个高度平衡的二分查找树(BST)。 解题思路: 递归实现二叉查找树定义二叉查找树又称有序树,是一棵空树或者具有以下性质的二叉树:1)若任意节点的左子树不为...

LeetCode_Convert Sorted List to Binary Search Tree

LeetCode_Convert Sorted List to Binary Search Tree 解题思路

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 109 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...

109 Convert Sorted List to Binary Search Tree [Leetcode]

题目内容: Given a singly linked list where elements are sorted in ascending order, convert it to a hei...

LeetCode OJ:Convert Sorted List to Binary Search Tree

Convert Sorted List to Binary Search Tree   Given a singly linked list where elements are sorted ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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