-
Notifications
You must be signed in to change notification settings - Fork 22
/
expression tree
49 lines (42 loc) · 1.29 KB
/
expression tree
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
/*
Given a simple expression tree, which is also a full binary tree consisting of basic binary operators i.e., + , – ,* and / and some
integers, Your task is to evaluate the expression tree.
Input Format:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an integer
N denoting the no of nodes. Then in the next line are N space separated values of the nodes of the Binary tree filled in continous way
from the left to the right.
Output Format:
For each test case output will be the result obtained by simplifying the expression tree.
Constraints:
1<=T<=100
2<=N<=50
Your Task:
You need to complete the function evalTree which takes the root of the tree as its only argument and returns an integer denoting the
result obtained by simplifying the expression tree.
Example(To be used only for expected Output):
Input:
2
7
+ * - 5 4 100 20
3
- 4 7
Output:
100
-3
*/
int evalTree(node* root)
{
if(!root) return 0;
if(root->left==NULL && root->right==NULL){
return stoi(root->data);
}
int l = evalTree(root->left);
int r = evalTree(root->right);
if(root->data == "+")
return l+r;
else if(root->data == "-")
return l-r;
else if(root->data == "*")
return l*r;
else return l/r;
}