处理无序树结构数据源(n复杂度查询根节点)

这里主要说数据源无序的情况下,如何找到根节点。

通常能想到的是这样的,以oc为例:

-(NSString*)findRootId:(NSArray*)array{
   

    NSString * [email protected]"";
    
    BOOL haveParent=NO;
    NSMutableArray *haveExistenceArray=[NSMutableArray array];

    for (YPTreeNode *data in array ) {
        
        [haveExistenceArray addObject:data.treeId];
        
        if (![haveExistenceArray containsObject:data.parentId]) {
            
            for (YPTreeNode *otherdata in array) {
                
                if([otherdata.treeId isEqualToString:data.parentId]){
                    haveParent=YES;
                    break;
                }
            }
            
            if (!haveParent) {
                str=data.parentId;
            }

        }
    }
    
    return str;

}

这种写法有序的情况下复杂度较小 1遍就能搞定,但是最差情况要n2级的复杂度。和朋友讨论,获得一个n复杂度的方法

-(NSString*)findRootId:(NSArray*)array{
    
        NSMutableDictionary *gxDic=[NSMutableDictionary dictionary];
    
        for (YPTreeNode *data in array ) {
            [gxDic setObject:data.parentId forKey:data.parentId];
        }
    
        for (YPTreeNode *data in array ) {
            [gxDic setObject:data.parentId forKey:data.treeId];
        }
    
        NSString *str=((YPTreeNode*)[array firstObject]).parentId;
    
        while ([gxDic objectForKey:str] != str) {
    
            str=[gxDic objectForKey:str] ;
        }
        return str;

}

附:(c语言算法)

#import <Foundation/Foundation.h>

//关系换成图结构更省空间
int a[10];

void insertRood() {
    // 1 --> 2
    a[2] = 1;
    // 3 --> 1
    a[3] = 1;
    a[4] = 2;
    a[5] = 2;
    a[6] = 3;
}

int findRoot(int child) {
    while (a[child] != child) {
        child = a[child];
    }
    return child;
}
int main(int argc, const char * argv[]) {
   
    for (int i = 0; i < 10; i++) {
        a[i] = i;
    }
    
    insertRood();
    //随便找一个节点就可以
    int root = findRoot(6);
    printf("root: %d\n",root);
    return 0;
}

使用以上方法,开源一个树视图代码:

git:YPThreeView

点赞