Hallo,
wie kann ich einen Baum aufstellen?
Irgendwo ist da noch ein Fehler im Code:
wie kann ich einen Baum aufstellen?
Irgendwo ist da noch ein Fehler im Code:
Code:
type
TParserTree = class;
TTreeType = (OperatorNode, NumberNode, VariableNode);
TOperator = record
left: TParserTree;
right: TParserTree;
operator: Char;
end;
TParserTree = class
ntype: TTreeType;
body: TOperator;
value: Variant;
end;
var
tree, pleft, pright: TParserTree;
function make_operator(left: TParserTree; op: Char; right: TParserTree): TParserTree;
begin
result := TParserTree.Create;
result.ntype := operatorNode;
result.body.left := left;
result.body.left.body.operator := op;
result.body.right := right;
end;
function make_number(n: Integer): TParserTree;
begin
result := TParserTree.Create;
result.ntype := numberNode;
result.value := n;
end;
function make_variable (v: String): TParserTree;
begin
result := TParserTree.Create;
result.ntype := variableNode;
result.value := v;
end;
function printTree(t: TParserTree; level: Integer): String;
var
step, i: Integer;
s: String;
begin
step := 4;
for i := 1 to level+step do
s := s + ' ';
if Assigned(t) then
begin
case t.ntype of
operatorNode:
begin
result := result + printTree(t.body.right, level+step);
result := result + Format('%s %s'+#10, [s,char(t.body.operator)]);
result := result + printTree(t.body.left, level+step);
end;
numberNode: begin
result := result + Format('%s %d', [s, Integer(t.value)]);
end;
variableNode: begin
showmessage('variableNode; ' + t.value);
result := result + printTree(t.body.right, level+step);
result := result + Format('%s %s', [s, String(t.value)]);
result := result + printTree(t.body.left , level+step);
end;
end;
end;
end;
begin
pleft := TParserTree.Create; pleft .value := 2; pleft .ntype := numberNode;
pright := TParserTree.Create; pright.value := 3; pright.ntype := numberNode;
tree := make_operator(pleft,'+',pright);
pl2 := TParserTree.Create; pl2.value := 4; pl2.ntype := numberNode;
tree := make_operator(tree,'*',pl2);
ShowMessage('1. Tree:'+#10+printTree(tree,4));
end;