[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 expression array, build the expression tree of this expression, return the root of this expression tree.

Have you met this question in a real interview?

Yes

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 [-].

这是个老题了,原先计算的结果是当做一个数字push到数据栈当中的,现在变成了节点。而且这里的特点是,根部没有计算问题,只需要在优先级的基础上构建表达式树。

 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 import java.util.*;
13
14 public class Solution {
15     /**
16      * @param expression: A string array
17      * @return: The root of expression tree
18      */
19     public ExpressionTreeNode build(String[] expression) {
20         // write your code here
21         Stack<ExpressionTreeNode> op   = new Stack<ExpressionTreeNode>();
22         Stack<ExpressionTreeNode> data = new Stack<ExpressionTreeNode>();
23         for(int i=0;i<expression.length;i++){
24             String tmp = expression[i];
25             char firstc = tmp.charAt(0);
26             if(!(firstc<=‘9‘&&firstc>=‘0‘)){
27                 //System.out.println("get op "+ tmp);
28                 switch(firstc){
29                     case ‘(‘:
30                         ExpressionTreeNode node = new ExpressionTreeNode(tmp);
31                         op.push(node);
32                         break;
33                     case ‘+‘:
34                     case ‘-‘:
35                         while(!op.isEmpty()&&op.peek().symbol.charAt(0)!=‘(‘){
36                             ExpressionTreeNode opnode = op.pop();
37                             ExpressionTreeNode data1 = data.pop();
38                             ExpressionTreeNode data2 = data.pop();
39                             opnode.left = data2;
40                             opnode.right = data1;
41                             data.push(opnode);
42                         }
43                         ExpressionTreeNode node2 = new ExpressionTreeNode(tmp);
44                         op.push(node2);
45                         break;
46                     case ‘*‘:
47                     case ‘/‘:
48                         while(!op.isEmpty()&&(op.peek().symbol.charAt(0)==‘*‘||op.peek().symbol.charAt(0)==‘/‘)){
49                             ExpressionTreeNode opnode = op.pop();
50                             ExpressionTreeNode data1 = data.pop();
51                             ExpressionTreeNode data2 = data.pop();
52                             opnode.left = data2;
53                             opnode.right = data1;
54                             data.push(opnode);
55                         }
56                         ExpressionTreeNode node3 = new ExpressionTreeNode(tmp);
57                         op.push(node3);
58                         break;
59                     case ‘)‘:
60                         while(op.peek().symbol.charAt(0)!=‘(‘){
61                             ExpressionTreeNode opnode = op.pop();
62                             ExpressionTreeNode data1 = data.pop();
63                             ExpressionTreeNode data2 = data.pop();
64                             opnode.left = data2;
65                             opnode.right = data1;
66                             data.push(opnode);
67                         }
68                         op.pop();
69                 }
70             }else{
71                 //System.out.println("add data "+tmp);
72                 ExpressionTreeNode data1 = new ExpressionTreeNode(tmp);
73                 data.push(data1);
74             }
75         }
76         while(!op.isEmpty()){
77             ExpressionTreeNode opnode = op.pop();
78             ExpressionTreeNode data1 = data.pop();
79             ExpressionTreeNode data2 = data.pop();
80             opnode.left = data2;
81             opnode.right = data1;
82             data.push(opnode);
83         }
84         if(data.isEmpty()) return null;
85         return data.pop();
86     }
87 }
时间: 2024-10-23 12:17:08

[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 expression array, buil

[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

Lintcode: Segment Tree Build

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 is given by build meth

[LintCode] Segment Tree Build 建立线段树

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 is given by build meth

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

Lintcode: Segment Tree Modify

For a Maximum Segment Tree, which each node has an extra value max to store the maximum value in this node's interval. Implement a modify function with three parameter root, index and value to change the node's value with [start, end] = [index, index

使用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)直