Evaluation of Expression Tree

Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.

Examples:

Input :
Root node of the below tree
Output :
100 Input :
Root node of the below tree
Output :
110

We strongly recommend you to minimize your browser and try this yourself first.

As all the operators in the tree are binary hence each node will have either 0 or 2 children. As it can be inferred from the examples above , the integer values would appear at the leaf nodes , while the interior nodes represent the operators.
To evaluate the syntax tree , a recursive approach can be followed .

Algorithm :
Let t be the syntax tree
If t is not null then
If t.info is operand then
Return t.info
Else
A = solve(t.left)
B = solve(t.right)
return A operator B
where operator is the info contained in t

The time complexity would be O(n), as each node is visited once. Below is a C++ program for the same:

 #include <iostream>
#include <cstdlib>
using namespace std; typedef struct node{
string s;
node *left;
node *right;
node(string x): s(x), left(NULL), right(NULL){}
}Node; // Utility function to return the integer value
// of a given string
int toInt(string s){
int len = s.length();
int num = ;
for(int i = ; i < len; i++){
num = num * + (s[i]-'');
}
return num;
} // Check which operator to apply
int calculate(const char *c, int lval, int rval){
int ans;
switch(*c){
case '+': ans = lval + rval; break;
case '-': ans = lval - rval; break;
case '*': ans = lval * rval; break;
case '/': ans = lval / rval; break;
}
return ans;
} // This function receives a node of the syntax tree
// and recursively evaluates it
int eval(Node *root){
// empty tree
if(root == NULL)
return ;
// leaf node i.e, an integer
if(root->left == NULL && root->right == NULL)
return toInt(root->s);
// Evaluate left subtree
int lval = eval(root->left);
// Evaluate right subtree
int rval = eval(root->right);
return calculate((root->s).c_str(), lval, rval);
} int main()
{
// create a syntax tree
node *root = new node("+");
root->left = new node("*");
root->left->left = new node("");
root->left->right = new node("");
root->right = new node("-");
root->right->left = new node("");
root->right->right = new node("");
cout << eval(root) << endl; delete(root); root = new node("+");
root->left = new node("*");
root->left->left = new node("");
root->left->right = new node("");
root->right = new node("-");
root->right->left = new node("");
root->right->right = new node("/");
root->right->right->left = new node("");
root->right->right->right = new node(""); cout << eval(root);
system("pause");
return ;
}

100

110

参考:http://www.geeksforgeeks.org/evaluation-of-expression-tree/

Evaluation of Expression Tree的更多相关文章

  1. Expression Tree Basics 表达式树原理

    variable point to code variable expression tree data structure lamda expression anonymous function 原 ...

  2. Expression Tree 扩展MVC中的 HtmlHelper 和 UrlHelper

    表达式树是LINQ To everything 的基础,同时各种类库的Fluent API也 大量使用了Expression Tree.还记得我在不懂expression tree时,各种眼花缭乱的A ...

  3. 使用Expression Tree构建动态LINQ查询

    这篇文章介绍一个有意思的话题,也是经常被人问到的:如何构建动态LINQ查询?所谓动态,主要的意思在于查询的条件可以随机组合,动态添加,而不是固定的写法.这个在很多系统开发过程中是非常有用的. 我这里给 ...

  4. Reflection和Expression Tree解析泛型集合快速定制特殊格式的Json

    很多项目都会用到Json,而且大部分的Json都是格式固定,功能强大,转换简单等,标准的key,value集合字符串:直接JsonConvert.SerializeObject(List<T&g ...

  5. .NET Expression Tree

    Expression Tree 第一个简单的例子. [TestMethod] public void GodTest() { Expression<Func<int, int, int&g ...

  6. 转载Expression Tree揭秘

    概述 在.NET Framework 3.5中提供了LINQ 支持后,LINQ就以其强大而优雅的编程方式赢得了开发人员的喜爱,而各种LINQ Provider更是满天飞,如LINQ to NHiber ...

  7. 深入学习C#匿名函数、委托、Lambda表达式、表达式树类型——Expression tree types

    匿名函数 匿名函数(Anonymous Function)是表示“内联”方法定义的表达式.匿名函数本身及其内部没有值或者类型,但是可以转换为兼容的委托或者表达式树类型(了解详情).匿名函数转换的计算取 ...

  8. Expression Tree Build

    The structure of Expression Tree is a binary tree to evaluate certain expressions.All leaves of the ...

  9. 表达式树(Expression Tree)

    饮水思源 本文并非原创而是下面网址的一个学习笔记 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/e ...

随机推荐

  1. MVC神韵---你想在哪解脱!(十一)

    为了实现这一处理,我们需要在MoviesController类中追加第二个Create方法.这个Create方法具有一个[HttpPost]属性,它意味着我们将要用它来处理提交到“/Movies/Cr ...

  2. .NET的Snk使用方法

    保护你Asp.Net生成的DLL和Code不被别人反编译  大家做项目开发一般都是分层的,比如UI层,业务层,数据访问层.业务层引用数据访问层的DLL(比如 dataAccess.dll),并使用da ...

  3. delete数组引发的core分析

    delete [] ptr 引发了singnal 6 abort的core错误,跟踪过程发现写入ptr大量数据,引发内存越界,破坏了new数组的尾部数据保护,导致delete的时候core. 问题分析 ...

  4. Thinkphp框架 -- ajax无刷新上传图片

    用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> < ...

  5. UOJ #142. 【UER #5】万圣节的南瓜灯 并查集

    #142. [UER #5]万圣节的南瓜灯 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://uoj.ac/problem/142 Descrip ...

  6. delphi 13 打印相关

    打印 页面设置 打印预览 文档属性     //---------------------------------------------------------------------------- ...

  7. range-bar

    https://github.com/edmodo/range-bar

  8. 模式识别 - 处理多演示样例学习(MIL)特征(matlab)

    处理多演示样例学习(MIL)特征(matlab) 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27206325 多演示样例学习( ...

  9. iOS开发——网络编程Swift篇&(三)同步Get方式

    同步Get方式 // MARK: - 同步Get方式 func synchronousGet() { //创建NSURL对象 var url:NSURL! = NSURL(string: " ...

  10. Jquery 回到顶部

    转:http://www.cnblogs.com/DemoLee/archive/2012/04/20/2459082.html 用jQuery实现渐隐渐显的返回顶部效果(附多图)   先来看几个图片 ...