1

我使用CFTree. 我必须逐层遍历那棵树。我应该如何实现广度优先算法?(请提供至少线索)目前我下面的代码使用深度优先。

- (CFTreeRef)createTreeFromJson:(NSDictionary *)jsonDict
{
    treeBacking = CreateMyTree(kCFAllocatorDefault, @"A");

    CFTreeRef bNode = CreateChildWithColor(treeBacking, @"B");
    CFTreeRef cNode = CreateChildWithColor(treeBacking, @"C");

    CreateChildWithColor(bNode, @"D");
    CreateChildWithColor(bNode, @"E");
    CreateChildWithColor(cNode, @"F");

    TraverseTree(treeBacking);

    return treeBacking;
}

static CFTreeRef CreateMyTree(CFAllocatorRef allocator, NSString *name) {

    NSString *info;
    CFTreeContext ctx;

    NSString *treeString = [[NSString alloc] initWithString:name];
    info = treeString;

    ctx.version = 0;
    ctx.info = (__bridge void *)(info);
    ctx.retain = CFRetain;
    ctx.release = CFRelease;
    ctx.copyDescription = NULL;

    return CFTreeCreate(allocator, &ctx);
}

static CFTreeRef CreateChildWithColor(CFTreeRef tree, NSString *name)
{
    CFTreeRef child;
    CFTreeContext ctx;
    child = CreateMyTree(CFGetAllocator(tree), name);
    CFTreeGetContext(child, &ctx);
    ctx.info = (__bridge void *)(name);
    CFTreeAppendChild(tree, child);
    return child;
}

static void TraverseTree(CFTreeRef tree) {
    // If the node has children, then next node is the first child
    CFTreeRef curChild = CFTreeGetFirstChild(tree);
    for (; curChild; curChild = CFTreeGetNextSibling(curChild)) {
        CFTreeContext ctx;
        CFTreeGetContext(curChild, &ctx);
        NSLog(@"Node Name : %@",ctx.info);

        TraverseTree(curChild);
    }
}
4

0 回答 0