我有一个对象调用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;
}
我没有正确地获得深度并尝试了许多算法,但无法获得深度正确。任何帮助表示赞赏。
答案 0 :(得分: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;
}