Skip to content

Commit 8f0c0b8

Browse files
committed
1. LinkedListCycle
2. SymmetricTree 3. UniqueBinarySearchTrees
1 parent 3e755a1 commit 8f0c0b8

File tree

3 files changed

+102
-0
lines changed

3 files changed

+102
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package net.kenyang.algorithm;
2+
3+
4+
public class LinkedListCycle {
5+
class ListNode {
6+
int val;
7+
ListNode next;
8+
9+
ListNode(int x) {
10+
val = x;
11+
next = null;
12+
}
13+
}
14+
15+
16+
public boolean hasCycle(ListNode head) {
17+
18+
ListNode slowNode = head;
19+
ListNode fastNode = head;
20+
if (head !=null && head.next != null) {
21+
fastNode = head.next;
22+
} else {
23+
return false;
24+
}
25+
26+
while (slowNode !=null && fastNode!=null){
27+
if (slowNode.val == fastNode.val ) return true;
28+
29+
slowNode = slowNode.next;
30+
fastNode = fastNode.next;
31+
if (fastNode!=null){
32+
fastNode = fastNode.next;
33+
}
34+
}
35+
36+
return false;
37+
}
38+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package net.kenyang.algorithm;
2+
3+
public class SymmetricTree {
4+
5+
public class TreeNode {
6+
int val;
7+
TreeNode left;
8+
TreeNode right;
9+
10+
TreeNode(int x) {
11+
val = x;
12+
}
13+
}
14+
15+
public boolean isSymmetric(TreeNode root) {
16+
if (root == null) {
17+
return true;
18+
}
19+
20+
return isSymmetric(root.left, root.right);
21+
}
22+
23+
public boolean isSymmetric(TreeNode leftNode, TreeNode rightNode) {
24+
if (rightNode == null && leftNode == null)
25+
return true;
26+
if (rightNode == null)
27+
return false;
28+
if (leftNode == null)
29+
return false;
30+
31+
32+
return leftNode.val == rightNode.val
33+
&& isSymmetric(leftNode.left, rightNode.right)
34+
&& isSymmetric(leftNode.right, rightNode.left);
35+
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package net.kenyang.algorithm;
2+
3+
/**
4+
* Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
5+
*
6+
* For example,
7+
* Given n = 3, there are a total of 5 unique BST's.
8+
* @author Ken Yang
9+
*
10+
*/
11+
public class UniqueBinarySearchTrees {
12+
13+
14+
public int numTrees(int n) {
15+
16+
if (n<2) {
17+
return 1;
18+
}
19+
int ans = 0;
20+
for(int i = 0; i < n; i++) {
21+
ans += numTrees(i) * numTrees(n-i-1);
22+
}
23+
return ans;
24+
25+
}
26+
27+
}

0 commit comments

Comments
 (0)