Top down or buttom up?

Tag: algorithm , sorting , binary-search-tree Author: nash0820 Date: 2012-07-01


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

Best Answer

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:

public static TreeNode addToTree(int arr[], int start, int end){ 
    if (end < start) {
        return null;
    }

    int mid = (start + end) / 2; 
    TreeNode left = addToTree(arr, start, mid - 1); 
    TreeNode right = addToTree(arr, mid + 1, end); 
    TreeNode n = new TreeNode(arr[mid]);
    n.left = left;
    n.right = right;
    return n;
}

In this approach, the bottom nodes of the tree would be created first, and the tree would be built upwards.

comments:

Alternatively, the root node is created first, and roots are at the bottom of trees, which branch out from them. Have you seen a tree which branched out from its top until it hit the ground?