Skiena's book on Algorithm contains the following question:
1) Evaluate expression given as binary tree in O(n) time, given n nodes.
2) Evaluate expression given as DAG in O(n+m) time, given n nodes and m edges in DAG.
I could think of a way for the first question:
evaluate(node) {
if(node has children){
left_val = evaluate(node->left);
right_val = evaluate(node->right);
// find operation symbol for node and use it as
// val = left_val operation right_val
return val;
}
else {
return node_value;
}
}
Since we visit each node once, it will take O(n) time.
Since the book has no solutions, can anyone please tell if this is correct ?
Also can anyone suggest a solution for second question.
Thanks.