Created
March 11, 2019 18:03
-
-
Save jianminchen/2cffe3c18cb7b7447cd76b7bfbbba6ff to your computer and use it in GitHub Desktop.
Leetcode 1008 - study Java code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/discuss/252479/Simple-Recursive-solution-in-Java-(more-verbose) | |
public TreeNode bstFromPreorder(int[] preorder) { | |
return bstFromPreorder(preorder, 0, preorder.length - 1); | |
} | |
public TreeNode bstFromPreorder(int[] order, int start, int end) { | |
if (start > end) { | |
return null; | |
} | |
TreeNode node = new TreeNode(order[start]); | |
int rightStart = start; | |
for (int i = start; i <= end; i++) { | |
if (order[start] < order[i]) { | |
break; | |
} | |
rightStart = i; | |
} | |
node.left = bstFromPreorder(order, start + 1, rightStart); | |
node.right = bstFromPreorder(order, rightStart + 1, end); | |
return node; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment