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

Commit4f6bf5e

Browse files
author
applewjg
committed
add inorder solution
Change-Id: I845e188989bfd6ba1f59f4ad1bf6992023220b57
1 parentb9f7dfb commit4f6bf5e

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

‎ConvertSortedArraytoBinarySearchTree.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
Notes:
88
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
99
10-
Solution: Recursion.
10+
Solution: Recursion. 1. preorder
11+
2. inorder
1112
*/
13+
1214
/**
1315
* Definition for binary tree
1416
* public class TreeNode {
@@ -19,7 +21,7 @@
1921
* }
2022
*/
2123
publicclassSolution {
22-
publicTreeNodesortedArrayToBST(int[]num) {
24+
publicTreeNodesortedArrayToBST_1(int[]num) {
2325
returnsortedArrayToBSTRe(num,0,num.length -1);
2426
}
2527
publicTreeNodesortedArrayToBSTRe(int[]num,intleft,intright) {
@@ -31,4 +33,19 @@ public TreeNode sortedArrayToBSTRe(int[] num, int left, int right) {
3133
node.right =sortedArrayToBSTRe(num,mid +1,right);
3234
returnnode;
3335
}
36+
publicTreeNodesortedArrayToBST(int[]num) {
37+
int[]curidx =newint[1];
38+
curidx[0] =0;
39+
returnsortedArrayToBSTRe1(num,num.length,curidx);
40+
}
41+
publicTreeNodesortedArrayToBSTRe1(int[]num,intlen,int[]curidx) {
42+
if (len ==0)returnnull;
43+
if (len ==1)returnnewTreeNode(num[curidx[0]++]);
44+
intmid =len /2;
45+
TreeNodeleft =sortedArrayToBSTRe1(num,mid,curidx);
46+
TreeNodenode =newTreeNode(num[curidx[0]++]);
47+
node.left =left;
48+
node.right =sortedArrayToBSTRe1(num,len -1 -mid,curidx);
49+
returnnode;
50+
}
3451
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp