BST深度以上的尺寸是多少?

时间:2016-07-29 05:01:42

标签: java data-structures binary-search-tree 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);
    }
}

编辑:此代码适用于并计算深度为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);
  }

2 个答案:

答案 0 :(得分:0)

我会想到更像这样的事情会......但也许我不能正确理解这个问题。

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;
    }
}

答案 1 :(得分:0)

此代码计算树的大小,直到深度为k,其中root位于深度为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--;
    }
}
相关问题