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

Posted bruce128

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode OJ 108. Convert Sorted Array to Binary Search Tree DFS求解相关的知识,希望对你有一定的参考价值。

    题目链接: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求解的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 108. Convert Sorted Array to Binary Search Tree

Leetcode 108. Convert Sorted Array to Binary Search Tree

LeetCode_108. Convert Sorted Array to Binary Search Tree

[LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree

Leetcode 108. Convert Sorted Array to Binary Search Tree

leetcode108. Convert Sorted Array to Binary Search Tree