Domanda

I'm trying to charge a binary tree in an ascendent form from a file of Integers, but it doesn't works.

program trees;

type 
        fl = file of Integer
    ;   ltree = ^puntTree
    ;   puntTree = record
                val : Integer
            ;   big : ltree
            ; low : ltree
        end
    ;

procedure openFile ( var iFile: fl; name: String; var error: Boolean );
    begin
        error := false;
        assign ( iFile, name );
        {$I-}
            reset ( iFile );
        {$I+}   
        if ( ioResult <> 0 ) then
            error := true;
    end;


procedure loadTree ( var tree: ltree; var iFile: fl; var principalNode: ltree; position: Integer );
    var val
                :Integer
        ;   node
                :ltree
        ;
    begin
        if ( tree = nil ) then
            begin
                seek ( iFile, position );
                read ( iFile, val );
                new ( tree );
                tree^.val := val;
                tree^.low := nil;
                tree^.big := nil;
            end;

        if not eof ( iFile ) then
            begin
                read ( iFile, val );

                node := principalNode;

                while ( node <> nil ) do
                    if ( node^.val < val ) then
                        node := node^.big
                    else
                        node := node^.low;

                cargartree ( node, iFile, principalNode, ( position + 1 ) );
            end;
    end;

procedure printTree ( tree: ltree );
    begin
        if ( tree <> nil ) then
            begin
                printTree ( tree^.low );
                writeln ( tree^.val, ' - ' );
                printTree ( tree^.big );
            end;
    end;

var 
        tree
    ,   principalNode
            :ltree
    ;   iFile
            :fl
    ;   fileName
            :String
    ;   error
            :Boolean
    ;

begin
    readln ( fileName );
    abrirfile ( iFile, fileName, error );
    if not error then
        loadTree ( tree, principalNode, iFile, 0 );
    printTree(principalNode);
end.

This is the code.

The file have 9 elements:

1 5 9 20 58 95 1 3 8

But when I print the tree, the console shows only:

1 - 

There's a way to fix it? Thanks!

È stato utile?

Soluzione

After trying to imagine what the code given is supposed to do as opposed to what it actually does, the primary error is that you are passing 'principalnode' to 'printtree'; you should be passing 'tree' to this procedure.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top