forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_1628.java
85 lines (72 loc) · 2.44 KB
/
_1628.java
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
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class _1628 {
public static class Solution1 {
/**
* Being able to think of resorting to Stack data structure is the key here to a straightforward solution.
*/
public abstract static class Node {
public abstract int evaluate();
public abstract List<String> print(Node node, List<String> list);
// define your fields here
Node left;
Node right;
String val;
}
static class NodeImpl extends Node {
@Override
public int evaluate() {
return dfs(this);
}
private int dfs(Node node) {
if (node == null) {
return 0;
}
if (node.left == null && node.right == null) {
return Integer.parseInt(node.val);
}
String op = node.val;
int left = dfs(node.left);
int right = dfs(node.right);
if (op.equals("+")) {
return left + right;
} else if (op.equals("-")) {
return left - right;
} else if (op.equals("*")) {
return left * right;
} else {
return left / right;
}
}
public NodeImpl(String val) {
this.val = val;
}
@Override
public List<String> print(Node node, List<String> list) {
if (node == null) {
return list;
}
print(node.left, list);
list.add(node.val);
print(node.right, list);
return list;
}
}
public static class TreeBuilder {
public Node buildTree(String[] postfix) {
Deque<Node> stack = new LinkedList<>();
for (String str : postfix) {
Node node = new NodeImpl(str);
if (!Character.isDigit(str.charAt(0))) {
node.right = stack.pollLast();
node.left = stack.pollLast();
}
stack.addLast(node);
}
return stack.pop();
}
}
}
}