树,根据某个子节点查找其所有父节点

用OC写的,具体代码如下:

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, strong) NSMutableArray *allParent;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 树, id,name  根据子节点查找所有父节点id
    
    NSArray *tree = @[@{@"id":@"1", @"name":@"node1", @"parent":@"0", @"nodes":@[
    @{@"id":@"2", @"name":@"node2", @"parent":@"1", @"nodes":@[@{@"id":@"4", @"name":@"node4", @"parent":@"2", @"nodes":@[]},@{@"id":@"5", @"name":@"node5", @"parent":@"2", @"nodes":@[]},]},
    @{@"id":@"3", @"name":@"node3", @"parent":@"1", @"nodes":@[@{@"id":@"6", @"name":@"node6", @"parent":@"3", @"nodes":@[]},@{@"id":@"7", @"name":@"node7", @"parent":@"3", @"nodes":@[]},]}
    ]}];
    
    self.allParent = [NSMutableArray array];
    [self findNode:@"node7" fromTree:tree];
    NSLog(@"%@", self.allParent);
}

- (BOOL)findNode:(NSString *)nodeName fromTree:(NSArray *)tree {
    for (NSDictionary *node in tree) {
        if ([node[@"name"] isEqualToString:nodeName]) {
            [self.allParent addObject:node[@"id"]];
            return YES;
        }
        
        NSArray *nodes = node[@"nodes"];
        BOOL find = [self findNode:nodeName fromTree:nodes];
        if (find) {
            [self.allParent insertObject:node[@"id"] atIndex:0];
            return YES;
        }
    }
    return NO;
}

@end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值