1

我有一个名为 CEKnot 的对象,它有一个名为 subknots 的属性,它是一个类似 CEKnot 对象的数组。现在我想计算这棵树的深度。这不是二叉树,因为子结可以超过两个。这是我尝试过的代码..

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CEProjectDTO* project = [self.tblViewDatasource objectAtIndex:indexPath.row];

    CEServiceSession *serviceSession = [CEServiceSession new];

    [CEProgressHUD showWithTitle:@"Loading..."];

    [serviceSession.projectPhaseService getProjectPhasesWithProjectID:project.i3D onFinish:^(NSArray * phaseList){
        self.phaseDTOList = phaseList;
        NSLog(@"Count is %d",[self.phaseDTOList count]);
        [CEProgressHUD hide];
    }onError:^(NSString *title, NSString *message) {
        [CEProgressHUD hide];
        [CEAlertViewHelper showOKAlertViewWithTitle:title message:message];
    }];
    self.mindMapLevelObjectCount = nil;
    self.mindMapLevelObjectCount = [[NSMutableDictionary alloc] init];
    self.level  = 1;

    self.numberOfKnotsOnThisLevel = 0;

    CEProjectToKnotConverter* converter = [CEProjectToKnotConverter new];
    CEProjectKnot* baseKnot = [converter convertProject:project withPhases:self.phaseDTOList];

    self.numberOfKnotsOnThisLevel = self.numberOfKnotsOnThisLevel + [baseKnot.subKnots count];
    [self.mindMapLevelObjectCount setObject:[NSNumber numberWithInt:self.numberOfKnotsOnThisLevel] forKey:[NSString stringWithFormat:@"%d",self.level]];
    self.numberOfKnotsOnThisLevel = 0;

    self.level  = 2;


    [self calculateMindMapLevels:baseKnot];

    NSLog(@"MIND MAP LEVEL OBJE %@", self.mindMapLevelObjectCount);


    CEMindMapViewController *mindMapViewController = [[CEViewControllerManager sharedInstance] createViewController:[CEMindMapViewController class]];
    mindMapViewController.baseKnot = baseKnot;
    [self presentModalViewController:mindMapViewController animated:YES];


}
-(void)calculateMindMapLevels:(CEKnot*)projectKnot{


    for (CEKnot* subKnot in projectKnot.subKnots) {
        self.numberOfKnotsOnThisLevel = self.numberOfKnotsOnThisLevel + [subKnot.subKnots count];
        NSLog(@"Level %d total of nots %d  project not subknot %d", self.level,self.numberOfKnotsOnThisLevel, [subKnot.subKnots count]);
    }
        [self.mindMapLevelObjectCount setObject:[NSNumber numberWithInt:self.numberOfKnotsOnThisLevel] forKey:[NSString stringWithFormat:@"%d",self.level]];


    for (CEKnot* subKnot in projectKnot.subKnots) {
        [self calculateMindMapLevels:subKnot];
        self.numberOfKnotsOnThisLevel = 0;
    }
    self.level = _level +1;

}

我没有正确获得深度并尝试了多种算法但无法正确获得深度。任何帮助表示赞赏。

4

1 回答 1

3

只要您的树不存储其深度,您就必须获取每个结的级别并返回最高值。

一种递归的未经测试的方法

int numberOfLevels(CEKnot *knot, int parentLevel) {
  int ownLevel = parentLevel+1;
  int highestLevel = ownLevel;
  for (CEKnot* subKnot in knot) {
    int subLevel = numberOfLevels(subKnot, ownLevel);
    highestLevel = MAX(highestLevel, subLevel);
  }
  return highestLevel;
}
于 2012-12-18T15:40:29.917 回答