Skip to content

Commit d0fdb9b

Browse files
committed
Java solution 145 && 150
1 parent b3c8c19 commit d0fdb9b

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import java.util.LinkedList;
2+
import java.util.List;
3+
import java.util.Stack;
4+
5+
/**
6+
* Given a binary tree, return the postorder traversal of its nodes' values.
7+
* <p>
8+
* For example:
9+
* Given binary tree {1,#,2,3},
10+
* 1
11+
* \
12+
* 2
13+
* /
14+
* 3
15+
* return [3,2,1].
16+
* <p>
17+
* Note: Recursive solution is trivial, could you do it iteratively?
18+
* <p>
19+
* Created by drfish on 6/8/2017.
20+
*/
21+
public class _145BinaryTreePostorderTraversal {
22+
public List<Integer> postorderTraversal(TreeNode root) {
23+
List<Integer> result = new LinkedList<>();
24+
Stack<TreeNode> stack = new Stack<>();
25+
while (root != null || !stack.isEmpty()) {
26+
while (root != null) {
27+
stack.push(root);
28+
result.add(0, root.val);
29+
root = root.right;
30+
}
31+
root = stack.pop().left;
32+
}
33+
return result;
34+
}
35+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.Stack;
2+
3+
/**
4+
* Evaluate the value of an arithmetic expression in Reverse Polish Notation.
5+
* Valid operators are +, -, *, /. Each operand may be an integer or another expression.
6+
* <p>
7+
* Some examples:
8+
* ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
9+
* ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
10+
* <p>
11+
* Created by drfish on 6/8/2017.
12+
*/
13+
public class _150EvaluateReversePolishNotation {
14+
public int evalRPN(String[] tokens) {
15+
if (tokens == null) {
16+
return 0;
17+
}
18+
Stack<Integer> stack = new Stack<>();
19+
for (String token : tokens) {
20+
switch (token) {
21+
case "+":
22+
stack.push(stack.pop() + stack.pop());
23+
break;
24+
case "*":
25+
stack.push(stack.pop() * stack.pop());
26+
break;
27+
case "-":
28+
int second = stack.pop();
29+
int first = stack.pop();
30+
stack.push(first - second);
31+
break;
32+
case "/":
33+
second = stack.pop();
34+
first = stack.pop();
35+
stack.push(first / second);
36+
break;
37+
default:
38+
stack.push(Integer.valueOf(token));
39+
}
40+
}
41+
return stack.pop();
42+
}
43+
44+
public static void main(String[] args) {
45+
_150EvaluateReversePolishNotation solution = new _150EvaluateReversePolishNotation();
46+
assert 9 == solution.evalRPN(new String[]{"2", "1", "+", "3", "*"});
47+
assert 6 == solution.evalRPN(new String[]{"4", "13", "5", "/", "+"});
48+
}
49+
}

0 commit comments

Comments
 (0)