尺寸大于深度和尺寸低于深度

时间:2015-08-01 03:25:42

标签: java size binary-search-tree

我是Java的初学者,我正在尝试编写一个代码来计算深度小于给定深度的节点数和深度大于给定深度的节点数。



public static int sizeAboveDepth(Node t, int k) {
    // TODO: Complete this method.
    if (t == null) {
      return 0;
    }
    if (t.key > k)
      return (sizeAboveDepth(t.left, k - 1) + sizeAboveDepth(t.right, k - 1) + 1);
    else {
      return sizeAboveDepth(t.left, k - 1) + sizeAboveDepth(t.right, k-1);
    }
  }

  // EXERCISE 6: The method "sizeBelowDepth" is described above.
  // The number of nodes in the tree "below" depth k (not including k)
  // include node n if depth(n) > k.
  public static int sizeBelowDepth(Node t, int k) {
    // TODO: Complete this method.
    if (t == null) {
      return 0;
    }
    if (t.key > k)
      return (sizeBelowDepth(t.left, k-1) + sizeBelowDepth(t.right, k-1) + 1);
    else {
      return sizeBelowDepth(t.left, k-1) + sizeBelowDepth(t.right, k-1);
    }
  }




所以有人可以帮我解决吗?我现在有点疯狂了~~

2 个答案:

答案 0 :(得分:0)

public static int sizeAboveDepth(Node t, int depth, final int k) {
  if ( t != null && depth < k){
    return sizeAboveDepth( t.left, depth+1, k) + 
           sizeAboveDepth( t.right, depth+1, k) + 1;
  } else {
    return 0;
  }   
}

public static int sizeBelowDepth(Node t, int depth, final int k) {
  if (t == null) {
    return 0;
  }
  int below = sizeBelowDepth(t.left, depth+1, k) + 
              sizeBelowDepth(t.right, depth+1, k);
  if (depth > k){
    below++;
  }
  return below;
}

答案 1 :(得分:-1)

xml

我不确定,但我认为这可以帮助你。