Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Desolve/39b4b56e6af4cda414fbe3fdc93fa9a3 to your computer and use it in GitHub Desktop.
Save Desolve/39b4b56e6af4cda414fbe3fdc93fa9a3 to your computer and use it in GitHub Desktop.
1008 Construct Binary Search Tree from Preorder Traversal
/**
* 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