English 中文(简体)
评估表达型树
原标题:Evaluating expression trees

Skiena Skiena的《算法书》载有如下问题:

(1) 评价在O(n) 时间给定的二进制树表达式, 给定 n节点 。

2) 评价O(n+m) 时间、 给定的 n 节点和 m 边缘在 DAG 中作为 DAG 表达式的表达式。

""https://i.sstatic.net/vjOjF.jpg" alt="在这里输入图像描述"/ >

我可以想出办法解决第一个问题:

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;
     }
}

既然我们每次访问每个节点一次,需要O(n)时间。

既然这本书没有解决办法, 任何人都能知道这是否正确吗?

任何人也可以建议解决第二个问题。

谢谢

最佳回答

对我来说,第一种方式看起来还不错。

对于 DAG,如果您可以修改树来为每个节点添加缓存值,如果操作员节点有一个缓存值,您可以使用相同的算法使用小节点,如果操作员节点有缓存值,则不再重复。这应该是O(n+m)时间(每个节点最多一个算术操作,每个节点最多一个指针查找一个边缘)。

evaluate(node) {
     if (node has value) {
          return node->value;
     } else {
          left = evaluate(node->left);
          right = evaluate(node->right);

          // find operation symbol for node and use it as
          // val = left_val operation right_val

          node->value = val;
          return val;
     }
}
问题回答

暂无回答




相关问题
How to add/merge several Big O s into one

If I have an algorithm which is comprised of (let s say) three sub-algorithms, all with different O() characteristics, e.g.: algorithm A: O(n) algorithm B: O(log(n)) algorithm C: O(n log(n)) How do ...

Grokking Timsort

There s a (relatively) new sort on the block called Timsort. It s been used as Python s list.sort, and is now going to be the new Array.sort in Java 7. There s some documentation and a tiny Wikipedia ...

Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Enumerating All Minimal Directed Cycles Of A Directed Graph

I have a directed graph and my problem is to enumerate all the minimal (cycles that cannot be constructed as the union of other cycles) directed cycles of this graph. This is different from what the ...

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...

热门标签