-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1646.cpp
98 lines (86 loc) · 2.29 KB
/
1646.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <string>
#include <iostream>
#include <vector>
using namespace std;
/**
* 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() {
delete left;
delete right;
};
virtual int evaluate() const = 0;
protected:
// define your fields here
Node *left;
Node *right;
string value;
};
class MyNode : public Node
{
public:
MyNode(string v) {
value = v;
left = nullptr;
right = nullptr;
}
virtual ~MyNode() {}
virtual void setLeft(Node *left) {
this->left = left;
};
virtual void setRight(Node *right) {
this->right = right;
}
virtual int evaluate() const {
if (value[0] == '+') {
return left->evaluate() + right->evaluate();
} else if (value[0] == '-') {
return left->evaluate() - right->evaluate();
} else if (value[0] == '*') {
return left->evaluate() * right->evaluate();
} else if (value[0] == '/') {
return left->evaluate() / right->evaluate();
} else {
return atoi(value.c_str());
}
}
};
/**
* 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) {
const int N = postfix.size();
vector<MyNode *> v(N, nullptr);
for (auto i = 0; i < N; i++) {
v[i] = new MyNode(postfix[i]);
if (postfix[i][0] == '+' || postfix[i][0] == '-' || postfix[i][0] == '*' || postfix[i][0] == '/') {
int j = i - 1;
while (v[j] == nullptr)
j--;
v[i]->setRight(v[j]);
v[j] = nullptr;
j--;
while (v[j] == nullptr)
j--;
v[i]->setLeft(v[j]);
v[j] = nullptr;
}
}
return v[N - 1];
}
};
/**
* Your TreeBuilder object will be instantiated and called as such:
* TreeBuilder* obj = new TreeBuilder();
* Node* expTree = obj->buildTree(postfix);
* int ans = expTree->evaluate();
*/