objective-c implementation

  • 0
    - (void) helper1:(TreeNode *)root :(NSMutableString *) out{
        if (!root) {[out appendString:@"#,"]; return;}
        [out appendFormat:@"%li,",root.val];
        [self helper1:root.left :out];
        [self helper1:root.right :out];
    // Encodes a tree to a single string.
    - (NSString *)serialize:(TreeNode*)root{
        NSMutableString * out = [[NSMutableString alloc] init];
        [self helper1:root :out];
        return [out copy];
    - (TreeNode*) helper2:(NSMutableArray *)in {
        NSString *word = [in firstObject];
        [in removeObjectAtIndex:0];
        if ([word isEqualToString:@"#"]) return nil;
        TreeNode *root = [[TreeNode alloc] initWithValue:[word integerValue]];
        root.left = [self helper2:in];
        root.right = [self helper2:in];
        return root;
    // Decodes your encoded data to tree.
    - (TreeNode*) deserialize:(NSString*) data {
        NSMutableArray *in = [[data componentsSeparatedByString:@","] mutableCopy];
        return [self helper2:in];

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.