I am confusing with this problem from Leetscode.com, is this algorithm a Top-down or Buttom-up?
public static TreeNode addToTree(int arr[], int start, int end){
if (end < start) {
return null;
}
int mid = (start + end) / 2;
TreeNode n = new TreeNode(arr[mid]);
n.left = addToTree(arr, start, mid - 1);
n.right = addToTree(arr, mid + 1, end);
return n;
}
Thank you
That’s a top-down approach. This algorithm puts the middle element in a node, then it builds the left and right sub-trees. So the top node is created first, and then the tree grows downwards.
In a bottom up approach, the left and right sub-trees would be created first, then they would be added to their parent. It would be something like this:
In this approach, the bottom nodes of the tree would be created first, and the tree would be built upwards.