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

LeetCode OJ 108. Convert Sorted Array to Binary Search Tree DFS求解

时间:2016-02-26 10:33:45      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

    题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

108. Convert Sorted Array to Binary Search Tree

My Submissions
Total Accepted: 68378 Total Submissions: 187560 Difficulty: Medium

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems
Have you met this question in a real interview? 
Yes
 
No

Discuss


    很有意思的一道题目。要求根据一个有序数组,构造出一棵高度平衡的BST。

    每次找到数组的中间位置,这个便是BST的 根节点。左右孩子也很好找,根节点左边区域的中间节点便是左孩子,根节点的右边区域的中间节点便是右孩子。如此递归求解。

    我的AC代码

public class ConvertSortedArraytoBinarySearchTree {

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

	TreeNode dfs(int[] nums, int left, int right) {
		if (left > right) return null;
		int mid = (left + right) / 2;
		TreeNode root = new TreeNode(nums[mid]);
		root.left = dfs(nums, left, mid - 1);
		root.right = dfs(nums, mid + 1, right);
		return root;
	}
}


LeetCode OJ 108. Convert Sorted Array to Binary Search Tree DFS求解

标签:

原文地址:http://blog.csdn.net/bruce128/article/details/50739995

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