二叉树

作者: 高乔人 | 来源:发表于2019-11-19 11:50 被阅读0次
    @interface myTree : NSObject
    
    @property (nonatomic,assign) NSInteger value;
    @property (nonatomic,strong) myTree *leftMyTree;
    @property (nonatomic,strong) myTree *rightMyTree;
    
    
    +(myTree *)createTreeWithValue:(NSArray *)values;
    @end
    
    1. 暴露一个方法,创建一个树。
    + (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: 方法创建二叉树。
    水平有限,不足之处,还望指正。

    相关文章

      网友评论

          本文标题:二叉树

          本文链接:https://www.haomeiwen.com/subject/bbssbctx.html