Created
June 5, 2020 11:23
-
-
Save Desolve/39b4b56e6af4cda414fbe3fdc93fa9a3 to your computer and use it in GitHub Desktop.
1008 Construct Binary Search Tree from Preorder Traversal
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
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
int i = 0; | |
public TreeNode bstFromPreorder(int[] preorder) { | |
if (preorder == null || preorder.length == 0) return null; | |
return build(preorder, Integer.MAX_VALUE); | |
} | |
public TreeNode build(int[] preorder, int bound) { | |
if (i == preorder.length || preorder[i] > bound) return null; | |
TreeNode root = new TreeNode(preorder[i++]); | |
root.left = build(preorder, root.val); | |
root.right = build(preorder, bound); | |
return root; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment