-2

This is what I have so far. I need to computes the size of the tree above at depth k.

public static int above(Node t, int k) {
    if (t == null) { return 0; }
    if (t.key > k)
       return (above(t.left, k - 1) + above(t.right, k - 1) + 1);
    else {
       return above(t.left, k - 1) + above(t.right, k - 1);
    }
}

EDIT: This code works and computes the size of the tree at depth k.

  public static int at(Node t, int k) {
     if(t == null) return 0;
     if(k == 0) return 1;
     return at(t.left, k - 1) + at(t.right, k - 1);
  }
yummyyenni
  • 23
  • 7

2 Answers2

0

I would of thought something more like this would do it... but maybe I don't understand the problem correctly.

public static int above(Node t, int k) {
    if (t == null) { return 0; }
    if (k > 0) {
        return (above(t.left, k - 1) + above(t.right, k - 1) + 1);
    } else {
        return 1;
    }
}
Maybe_Factor
  • 370
  • 3
  • 10
  • hi, i added more explanation in my post in hopes it makes more sense. I need to computes the size of the tree above at depth k. so I added a + 1 but it didnt work – yummyyenni Jul 29 '16 at 05:28
0

This code computes the tree size till depth k where root is at depth 1.

static int depth=0;
static int tree_size=0,k=3;
private static void inorder(Node head) {
    if(head!=null){
        depth++;
        inorder(head.left);
        if(depth<=k)
            tree_size++;            
        inorder(head.right);
        depth--;
    }
}
Loki
  • 801
  • 5
  • 13