给定双亲结点数组P,求树的高度或者深度(JAVA)

代码实现

int findDepthInGenericTree(int p[],int n){
    
    
  int maxDepth - -1;
  int currentDepth = -1;
  int j = 0;
  for(int i = 0; i < n; i++){
    
    
    currentDepth = 0;
    j = i;
    //从当前结点回调到根结点,计算出树的深度
    while(p[j] != -1){
    
    
      currentDepth++;
      j = p[i];
    }
    if(currentDepth > maxDepth){
    
    
      maxDepth = currentDepth;
    }
    return maxDepth;
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/115035043