用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