标签:
题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
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
很有意思的一道题目。要求根据一个有序数组,构造出一棵高度平衡的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