@interface myTree : NSObject
@property (nonatomic,assign) NSInteger value;
@property (nonatomic,strong) myTree *leftMyTree;
@property (nonatomic,strong) myTree *rightMyTree;
+(myTree *)createTreeWithValue:(NSArray *)values;
@end
- 暴露一个方法,创建一个树。
+ (myTree *)createTreeWithValue:(NSArray *)values{
myTree *rootTree = nil;
for (int i = 0; i<values.count; i++) {
NSInteger value = [(NSNumber *) [values objectAtIndex:i] integerValue];
rootTree = [myTree addTreeNode:rootTree value:value];
}
return rootTree;
}
遍历外界数组,
+ (myTree *)addTreeNode:(myTree *)treeNode value:(NSInteger)value {
if (!treeNode) {
return nil;
}
//值小于根节点,则插入到左子树
else if (value <= treeNode.value){
treeNode.leftMyTree = [myTree addTreeNode:treeNode.leftMyTree value:value];
}
//值大于根节点,则插入到右子树
else if (value >= treeNode.value){
treeNode.rightMyTree = [myTree addTreeNode:treeNode.rightMyTree value:value];
}
return treeNode;
}
递归调用 addTreeNode:value: 方法创建二叉树。
水平有限,不足之处,还望指正。
网友评论