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-面试算法经典-Java实现】【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】

【108-Convert Sorted Array to Binary Search Tree(排序数组转变为平衡二叉树)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  ...

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

LeetCode(108)Convert Sorted Array to Binary Search Tree

题目如下: 分析如下: 递归进行。每次找到排序数组的中点,中点左边的子排序数组构成左子树,中点右边的子排序数组构成右子树。就这样递归进行。由于每次都几乎做到了二分,所以每次的左子树和右子树的节点数量是...

LeetCode108 Convert Sorted Array to Binary Search Tree

详细见:leetcode.com/problems/convert-sorted-array-to-binary-search-tree Java Solution: github p...

[LeetCode][Java] 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】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
  • 359
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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