-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay51.cc
More file actions
81 lines (61 loc) · 1.93 KB
/
Day51.cc
File metadata and controls
81 lines (61 loc) · 1.93 KB
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
/*
Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'.
Given the root to such a tree, write a function to evaluate it.
For example, given the following tree:
*
/ \
+ +
/ \ / \
3 2 4 5
You should return 45, as it is (3 + 2) * (4 + 5).
*/
#include <bits/stdc++.h>
using namespace std;
struct Node {
string val;
Node* left;
Node* right;
Node(string x) : val(x), left(nullptr), right(nullptr) {}
};
int evaluate(Node* root) {
if (!root) throw invalid_argument("Null node encountered");
if (!root->left && !root->right) {
try {
return stoi(root->val);
} catch (...) {
throw invalid_argument("Invalid integer leaf value: " + root->val);
}
}
if (!root->left || !root->right)
throw invalid_argument("Operator node must have two children: " +
root->val);
int leftVal = evaluate(root->left);
int rightVal = evaluate(root->right);
if (root->val == "+") return leftVal + rightVal;
if (root->val == "-") return leftVal - rightVal;
if (root->val == "*") return leftVal * rightVal;
if (root->val == "/") {
if (rightVal == 0) throw runtime_error("Division by zero");
return leftVal / rightVal;
}
throw invalid_argument("Unknown operator: " + root->val);
}
int main() {
Node* root = new Node("*");
root->left = new Node("+");
root->right = new Node("+");
root->left->left = new Node("3");
root->left->right = new Node("2");
root->right->left = new Node("4");
root->right->right = new Node("5");
int result = evaluate(root);
cout << "Result: " << result << endl;
delete root->left->left;
delete root->left->right;
delete root->right->left;
delete root->right->right;
delete root->left;
delete root->right;
delete root;
return 0;
}