Skip to content

Commit b9f7dfb

Browse files
author
applewjg
committed
ConvertSortedArraytoBinarySearchTree
Change-Id: Ie9080e731479150c99c89ccd69bf3136212b4167
1 parent 077ba38 commit b9f7dfb

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Author: Andy, [email protected]
3+
Date: Jan 29, 2015
4+
Problem: Convert Sorted Array to Binary Search Tree
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
7+
Notes:
8+
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
9+
10+
Solution: Recursion.
11+
*/
12+
/**
13+
* Definition for binary tree
14+
* public class TreeNode {
15+
* int val;
16+
* TreeNode left;
17+
* TreeNode right;
18+
* TreeNode(int x) { val = x; }
19+
* }
20+
*/
21+
public class Solution {
22+
public TreeNode sortedArrayToBST(int[] num) {
23+
return sortedArrayToBSTRe(num, 0, num.length - 1);
24+
}
25+
public TreeNode sortedArrayToBSTRe(int[] num, int left, int right) {
26+
if (left > right) return null;
27+
if (left == right) return new TreeNode(num[left]);
28+
int mid = (left + right) / 2;
29+
TreeNode node = new TreeNode(num[mid]);
30+
node.left = sortedArrayToBSTRe(num, left, mid - 1);
31+
node.right = sortedArrayToBSTRe(num, mid + 1, right);
32+
return node;
33+
}
34+
}

0 commit comments

Comments
 (0)