Untitled
public class Solution { private int index = 0; public TreeNode bstFromPreorder(int[] preorder) { return construct(preorder, Integer.MIN_VALUE, Integer.MAX_VALUE); } private TreeNode construct(int[] preorder, int lowerBound, int upperBound) { if (index >= preorder.length) return null; int val = preorder[index]; if (val < lowerBound || val > upperBound) return null; index++; // Move to the next element TreeNode node = new TreeNode(val); node.left = construct(preorder, lowerBound, val); // Left subtree node.right = construct(preorder, val, upperBound); // Right subtree return node; } }
Leave a Comment