SUNY Geneseo Department of Mathematics
Thursday, September 24
Math 303
Fall 2015
Prof. Doug Baldwin
value( root )
if root.type = “const”
return root.value
else if root.type = “+”
return value( root.left) + value( root.right )
else if root.type = “*”
return value( root.left ) * value( root.right )
else if root.type = “sin”
return sin( value( root.left ) )
...
function [ v ] = value( root )
if strcmp( root.type, 'const' ) == 1
v = root.value;
elseif strcmp( root.type, '+' ) == 1
v = value( root.left ) + value( root.right );
elseif strcmp( root.type, '*' ) == 1
v = value( root.left ) * value( root.right );
elseif strcmp( root.type, 'sin' ) == 1
v = sin( value( root.left ) );
else
display 'ERROR!';
end
end
>> root = struct( 'type', '+' )
root =
type: '+'
>> arg1 = struct( 'type', 'const', 'value', 12 )
arg1 =
type: 'const'
value: 12
>> arg2 = struct( 'type','const', 'value', 3 )
arg2 =
type: 'const'
value: 3
>> root.left = arg1; root.right=arg2;
>> value( root )
ans =
15
>> exp2 = struct( 'type', 'sin' );
>> arg3 = struct( 'type', 'const', 'value', 19 );
>> exp2.left = arg3;
>> root.right = exp2;
>> value( root )
ans =
12.1499
deriv( root ) // expression tree for root′
if root.type = “const”
return struct( “const”, 0 )
else if root.type = “x”
return struct( “const”, 1 )
else if root.type = “*”
return struct( “+”,
struct( “*”,
deriv( root.left ),
root.right ),
struct( “*”,
root.left,
deriv( root.right ) ) )
else if root.type = “+”
return struct( “+”, deriv( root.left ), deriv( root.right))
else if root.type = “sin”
return struct( “*”,
struct( “cos”, root.left ),
deriv( root.left ) )