forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
78 lines (69 loc) · 1.9 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* This is the interface for the expression tree Node.
* You should not remove it, and you can define some classes to implement it.
*/
class Node {
public:
virtual ~Node () {};
virtual int evaluate() const = 0;
protected:
// define your fields here
string val;
Node* left;
Node* right;
};
class MyNode : public Node {
public:
MyNode(string val) {
this->val = val;
}
MyNode(string val, Node* left, Node* right) {
this->val = val;
this->left = left;
this->right = right;
}
int evaluate() const {
if (!(val == "+" || val == "-" || val == "*" || val == "/")) return stoi(val);
auto leftVal = left->evaluate(), rightVal = right->evaluate();
if (val == "+") return leftVal + rightVal;
if (val == "-") return leftVal - rightVal;
if (val == "*") return leftVal * rightVal;
if (val == "/") return leftVal / rightVal;
return 0;
}
};
/**
* This is the TreeBuilder class.
* You can treat it as the driver code that takes the postinfix input
* and returns the expression tree represnting it as a Node.
*/
class TreeBuilder {
public:
Node* buildTree(vector<string>& postfix) {
stack<MyNode*> stk;
for (auto s : postfix)
{
MyNode* node;
if (s == "+" || s == "-" || s == "*" || s == "/")
{
auto right = stk.top();
stk.pop();
auto left = stk.top();
stk.pop();
node = new MyNode(s, left, right);
}
else
{
node = new MyNode(s);
}
stk.push(node);
}
return stk.top();
}
};
/**
* Your TreeBuilder object will be instantiated and called as such:
* TreeBuilder* obj = new TreeBuilder();
* Node* expTree = obj->buildTree(postfix);
* int ans = expTree->evaluate();
*/