-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcp-050-evaluate-tree.linq
62 lines (54 loc) · 1.24 KB
/
dcp-050-evaluate-tree.linq
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
<Query Kind="Program" />
// This problem was asked by Microsoft.
//
// 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
void Main()
{
var root = new Node("*",
new Node("+",
new Node("3"),
new Node("2")),
new Node("+",
new Node("4"),
new Node("5")));
root.Evaluate().Dump();
}
public class Node
{
public string Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(string value, Node left = null, Node right = null)
{
Value = value;
Left = left;
Right = right;
}
public int Evaluate()
{
if (Value == "+")
return Left.Evaluate() + Right.Evaluate();
else if (Value == "-")
return Left.Evaluate() - Right.Evaluate();
else if (Value == "/")
return Left.Evaluate() / Right.Evaluate();
else if (Value == "*")
return Left.Evaluate() * Right.Evaluate();
else if (Regex.IsMatch(Value, "[0-9]+"))
return int.Parse(Value);
else
throw new Exception($"Unexpected value: {Value}");
}
}