LeetCode Convert Sorted Array to Binary Search Tree

原创 2015年07月06日 16:35:12

Description:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

Solution:

每次dfs层次中,为了实现平衡,都是二分,取出中间的数值作为根节点的数值。

import java.util.*;

public class Solution {
	int nums[];

	public TreeNode sortedArrayToBST(int[] nums) {
		this.nums = nums;
		return dfs(0, nums.length - 1);
	}

	TreeNode dfs(int start, int end) {
		if(start>end)return null;
		int rootIndex = (start + end) / 2;

		TreeNode root = new TreeNode(nums[rootIndex]);
		root.left = dfs(start, rootIndex - 1);
		root.right = dfs(rootIndex + 1, end);
		return root;
	}
}



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

leetcode108~Convert Sorted Array to Binary Search Tree

/* * Given an array where elements are sorted in ascending order, convert it to a height balanced ...

LeetCode_Convert Sorted Array to Binary Search Tree

LeetCode_Convert Sorted Array to Binary Search Tree 解题思路

【Leetcode】【python】Convert Sorted Array to Binary Search Tree

题目大意将一个排序好的数组转换为一颗二叉查找树,这颗二叉查找树要求是平衡的。解题思路由于要求二叉查找树是平衡的。所以我们可以选在数组的中间那个数当树根root,然后这个数左边的数组为左子树,右边的数组...

【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 108 Convert Sorted Array to Binary Search Tree 有序数组构造平衡二叉查找树

给出一个有序数组(递增),使用该数组构造一个平衡二叉查找树。

[C++]LeetCode: 100 Convert Sorted Array to Binary Search Tree (AVL树)

题目:Given an array where elements are sorted in ascending order, convert it to a height balanced BS...

LeetCode OJ 之 Convert Sorted Array to Binary Search Tree(把有序数组转化为二叉搜索树)

题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BS...

[leetcode]108. Convert Sorted Array to Binary Search Tree@Java解题报告

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ Given a...

【LeetCode】108. Convert Sorted Array to Binary Search Tree 解法及注释,分治法,递归

108. Convert Sorted Array to Binary Search Tree Total Accepted: 73365 Total Submissions: 197776 Di...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Convert Sorted Array to Binary Search Tree
举报原因:
原因补充:

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