Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb9f7dfb

Browse files
author
applewjg
committed
ConvertSortedArraytoBinarySearchTree
Change-Id: Ie9080e731479150c99c89ccd69bf3136212b4167
1 parent077ba38 commitb9f7dfb

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, nkuwjg@gmail.com
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+
publicclassSolution {
22+
publicTreeNodesortedArrayToBST(int[]num) {
23+
returnsortedArrayToBSTRe(num,0,num.length -1);
24+
}
25+
publicTreeNodesortedArrayToBSTRe(int[]num,intleft,intright) {
26+
if (left >right)returnnull;
27+
if (left ==right)returnnewTreeNode(num[left]);
28+
intmid = (left +right) /2;
29+
TreeNodenode =newTreeNode(num[mid]);
30+
node.left =sortedArrayToBSTRe(num,left,mid -1);
31+
node.right =sortedArrayToBSTRe(num,mid +1,right);
32+
returnnode;
33+
}
34+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp