Expression Tree Build

The structure of Expression Tree is a binary tree to evaluate certain expressions.
All leaves of the Expression Tree have an number string value. All non-leaves of the Expression Tree have an operator string value.

Now, given an expression array, build the expression tree of this expression, return the root of this expression tree.

Clarification

See wiki:
Expression Tree

Example

For the expression (2*6-(23+7)/(1+2)) (which can be represented by ["2" "*" "6" "-" "(" "23" "+" "7" ")" "/" "(" "1" "+" "2" ")"]). 
The expression tree will be like

                 [ - ]
             /                  [ * ]              [ / ]
      /     \           /             [ 2 ]  [ 6 ]      [ + ]        [ + ]
                     /    \       /                         [ 23 ][ 7 ] [ 1 ]   [ 2 ] .

After building the tree, you just need to return root node [-].

分析:

先把expression 转成RPN,然后遇到operator,直接建立一颗树,数的root是operator, 左右节点从stack里面pop就可以,然后把该root压栈。

 1 /**
 2  * Definition of ExpressionTreeNode:
 3  * public class ExpressionTreeNode {
 4  *     public String symbol;
 5  *     public ExpressionTreeNode left, right;
 6  *     public ExpressionTreeNode(String symbol) {
 7  *         this.symbol = symbol;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12
13 /**
14  * Definition of ExpressionTreeNode:
15  * public class ExpressionTreeNode {
16  *     public String symbol;
17  *     public ExpressionTreeNode left, right;
18  *     public ExpressionTreeNode(String symbol) {
19  *         this.symbol = symbol;
20  *         this.left = this.right = null;
21  *     }
22  * }
23  */
24
25 public class Solution {
26     /**
27      * @param expression: A string array
28      * @return: The root of expression tree
29      */
30     public ExpressionTreeNode build(String[] expression) {
31
32         ArrayList<String> RPN = convertToRPN(expression);
33         if (RPN == null || RPN.size() == 0) return null;
34
35         Stack<ExpressionTreeNode> stack   = new Stack<ExpressionTreeNode>();
36         for (String str : RPN) {
37             if (isOperator(str)) {
38                 ExpressionTreeNode opnode = new ExpressionTreeNode(str);
39                 ExpressionTreeNode data1 = stack.pop();
40                 ExpressionTreeNode data2 = stack.pop();
41                 opnode.left = data2;
42                 opnode.right = data1;
43                 stack.push(opnode);
44             } else {
45                 stack.push(new ExpressionTreeNode(str));
46             }
47         }
48         return stack.pop();
49     }
50
51     public ArrayList<String> convertToRPN(String[] expression) {
52         ArrayList<String> list = new ArrayList<String>();
53         Stack<String> stack = new Stack<String>();
54
55         for (int i = 0; i < expression.length; i++) {
56             String str = expression[i];
57             if (isOperator(str)) {
58                 if (str.equals("(")) {
59                     stack.push(str);
60                 } else if (str.equals(")")) {
61                     while (!stack.isEmpty() && !stack.peek().equals("(")) {
62                         list.add(stack.pop());
63                     }
64                     stack.pop();
65                 } else {
66                     while (!stack.isEmpty() && order(str) <= order(stack.peek())) {
67                         list.add(stack.pop());
68                     }
69                     stack.push(str);
70                 }
71             } else {
72                 list.add(str);
73             }
74         }
75         while (!stack.isEmpty()) {
76             list.add(stack.pop());
77         }
78         return list;
79     }
80
81     private boolean isOperator(String str) {
82         if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/") || str.equals("(")
83                 || str.equals(")")) {
84             return true;
85         }
86         return false;
87     }
88
89     private int order(String a) {
90         if (a.equals("*") || a.equals("/")) {
91             return 2;
92         } else if (a.equals("+") || a.equals("-")) {
93             return 1;
94         } else {
95             return 0;
96         }
97     }
98 }
时间: 2024-10-09 19:02:39

Expression Tree Build的相关文章

[Lintcode] Expression Tree Build

Expression Tree Build The structure of Expression Tree is a binary tree to evaluate certain expressions. All leaves of the Expression Tree have an number string value. All non-leaves of the Expression Tree have an operator string value. Now, given an

Segment Tree Build I &amp; II

Segment Tree Build I The structure of Segment Tree is a binary tree which each node has two attributes start and end denote an segment / interval. start and end are both integers, they should be assigned in following rules: The root's start and end i

Evaluation of Expression Tree

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 t

使用Expression Tree构建动态LINQ查询

这篇文章介绍一个有意思的话题,也是经常被人问到的:如何构建动态LINQ查询?所谓动态,主要的意思在于查询的条件可以随机组合,动态添加,而不是固定的写法.这个在很多系统开发过程中是非常有用的. 我这里给的一个解决方案是采用Expression Tree来构建. 其实这个技术很早就有,在.NET Framework 3.5开始引入.之前也有不少同学写过很多不错的理论性文章.我自己当年学习这个,觉得最好的几篇文章是由"装配脑袋"同学写的.[有时间请仔细阅读这些入门指南,做点练习基本就能理解]

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

很多项目都会用到Json,而且大部分的Json都是格式固定,功能强大,转换简单等,标准的key,value集合字符串:直接JsonConvert.SerializeObject(List<T>)就可以搞定了,但凡事并非千篇一律,比如有的时候我们需要的Json可能只需要value,不需要key,并且前后可能还需要辅助信息等等,那该怎么办呢?我所能想到的可能有两种方案,1.自定义跟所需json格式一样的数据结构model,然后用JsonConvert.SerializeObject(model)直

[LintCode] Segment Tree Build II 建立线段树之二

The structure of Segment Tree is a binary tree which each node has two attributes startand end denote an segment / interval. start and end are both integers, they should be assigned in following rules: The root's start and end is given bybuild method

[深入学习C#]表达式树类型——Expression tree types

表达式树允许将 lambda 表达式表示为数据结构而非可执行代码.表达式目录树是System.Linq.Expressions.Expression< D > 形式的表达式目录树类型 (expression tree type) 的值,其中 D 是任何委托类型. 如果存在从 lambda 表达式到委托类型 D 的转换,则也存在到表达式树类型 Expression< D > 的转换.而lambda 表达式到委托类型的转换生成引用该 lambda 表达式的可执行代码的委托,到表达式树类

[转]打造自己的LINQ Provider(上):Expression Tree揭秘

概述 在.NET Framework 3.5中提供了LINQ 支持后,LINQ就以其强大而优雅的编程方式赢得了开发人员的喜爱,而各种LINQ Provider更是满天飞,如LINQ to NHibernate.LINQ to Google等,大有“一切皆LINQ”的趋势.LINQ本身也提供了很好的扩展性,使得我们可以轻松的编写属于自己的LINQ Provider. 本文为打造自己的LINQ Provider系列文章第一篇,主要介绍表达式目录树(Expression Tree)的相关知识. 认识表

Traverse an expression tree and extract parameters

Traverse an expression tree and extract parameters I think as you've said that using ExpressionVisitor works out to be a good approach. You don't need to implement all the Visit... methods as they already have a default implementation. From what I un