Skip to content

Commit ef34e89

Browse files
committed
Java solution 94 && 96
1 parent cf36854 commit ef34e89

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* Given a binary tree, return the inorder traversal of its nodes' values.
3+
* <p>
4+
* For example:
5+
* Given binary tree [1,null,2,3],
6+
* 1
7+
* \
8+
* 2
9+
* /
10+
* 3
11+
* return [1,3,2].
12+
* <p>
13+
* Note: Recursive solution is trivial, could you do it iteratively?
14+
* Created by drfish on 27/05/2017.
15+
*/
16+
17+
import java.util.ArrayList;
18+
import java.util.List;
19+
import java.util.Stack;
20+
21+
/**
22+
* Definition for a binary tree node.
23+
*/
24+
class TreeNode {
25+
int val;
26+
TreeNode left;
27+
TreeNode right;
28+
29+
TreeNode(int x) {
30+
val = x;
31+
}
32+
}
33+
34+
public class _094BinaryTreeInorderTraversal {
35+
public List<Integer> inorderTraversal(TreeNode root) {
36+
Stack<TreeNode> stack = new Stack<>();
37+
List<Integer> result = new ArrayList<>();
38+
while (root != null || !stack.empty()) {
39+
while (root != null) {
40+
stack.add(root);
41+
root = root.left;
42+
}
43+
root = stack.pop();
44+
result.add(root.val);
45+
root = root.right;
46+
}
47+
return result;
48+
}
49+
}

java/_096UniqueBinarySearchTrees.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
3+
* <p>
4+
* For example,
5+
* Given n = 3, there are a total of 5 unique BST's.
6+
* <p>
7+
* 1 3 3 2 1
8+
* \ / / / \ \
9+
* 3 2 1 1 3 2
10+
* / / \ \
11+
* 2 1 2 3
12+
* <p>
13+
* Created by drfish on 27/05/2017.
14+
*/
15+
public class _096UniqueBinarySearchTrees {
16+
public int numTrees(int n) {
17+
int[] counts = new int[n + 1];
18+
counts[0] = 1;
19+
for (int i = 1; i <= n; i++) {
20+
int count = 0;
21+
for (int j = 0; j < i; j++) {
22+
count += counts[j] * counts[i - 1 - j];
23+
}
24+
counts[i] = count;
25+
}
26+
return counts[n];
27+
}
28+
29+
public static void main(String[] args) {
30+
_096UniqueBinarySearchTrees uniqueBinarySearchTrees = new _096UniqueBinarySearchTrees();
31+
System.out.println(uniqueBinarySearchTrees.numTrees(6));
32+
assert uniqueBinarySearchTrees.numTrees(3) == 5;
33+
}
34+
}

0 commit comments

Comments
 (0)