Skip to content

Commit 3f6a304

Browse files
authored
Create problem_50
Evaluate binary tree given a root
1 parent 0ffe489 commit 3f6a304

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

daily_coding_problems/problem_50

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
Daily Coding Problem #50
2+
Problem
3+
This problem was asked by Microsoft.
4+
5+
Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'.
6+
7+
Given the root to such a tree, write a function to evaluate it.
8+
9+
For example, given the following tree:
10+
11+
*
12+
/ \
13+
+ +
14+
/ \ / \
15+
3 2 4 5
16+
You should return 45, as it is (3 + 2) * (4 + 5).
17+
18+
Solution
19+
This problem should be straightforward from the definition. It will be recursive. We check the value of the root node. If it's one of our arithmetic operators, then we take the evaluated value of our node's children and apply the operator on them.
20+
21+
If it's not an arithmetic operator, it has to be a raw number, so we can just return that.
22+
23+
class Node:
24+
def __init__(self, val, left=None, right=None):
25+
self.val = val
26+
self.left = left
27+
self.right = right
28+
29+
PLUS = "+"
30+
MINUS = "-"
31+
TIMES = "*"
32+
DIVIDE = "/"
33+
def evaluate(root):
34+
if root.val == PLUS:
35+
return evaluate(root.left) + evaluate(root.right)
36+
elif root.val == MINUS:
37+
return evaluate(root.left) - evaluate(root.right)
38+
elif root.val == TIMES:
39+
return evaluate(root.left) * evaluate(root.right)
40+
elif root.val == DIVIDE:
41+
return evaluate(root.left) / evaluate(root.right)
42+
else:
43+
return root.val
44+
This runs in O(N) time and space.
45+
46+
47+
48+
########
49+
root = Node('*')
50+
root.left = Node('+')
51+
root.right = Node('+')
52+
root.left.left = Node(3)
53+
root.left.right = Node(2)
54+
root.right.left = Node(4)
55+
root.right.right = Node(5)
56+
evaluate(root)

0 commit comments

Comments
 (0)