Untitled
unknown
plain_text
10 months ago
879 B
3
Indexable
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}
}
public class BSTFromInorder {
public TreeNode constructBST(int[] inorder) {
return buildTree(inorder, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] inorder, int start, int end) {
// Base condition: if start > end, return null
if (start > end) {
return null;
}
// Find the middle element as the root
int mid = start + (end - start) / 2;
TreeNode root = new TreeNode(inorder[mid]);
// Recursively build the left and right subtrees
root.left = buildTree(inorder, start, mid - 1);
root.right = buildTree(inorder, mid + 1, end);
return root;
}
}
Editor is loading...
Leave a Comment