Skip to content

Commit 5b0c3f0

Browse files
committed
Java solution 100 && 101
1 parent 77e5f42 commit 5b0c3f0

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

java/_100SameTree.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Given two binary trees, write a function to check if they are equal or not.
3+
* Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
4+
* <p>
5+
* Created by drfish on 28/05/2017.
6+
*/
7+
public class _100SameTree {
8+
public boolean isSameTree(TreeNode p, TreeNode q) {
9+
if (p == null && q == null) {
10+
return true;
11+
}
12+
if (p != null && q != null) {
13+
if (p.val == q.val) {
14+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
15+
}
16+
}
17+
return false;
18+
}
19+
}

java/_101SymmetricTree.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
3+
* <p>
4+
* For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
5+
* 1
6+
* / \
7+
* 2 2
8+
* / \ / \
9+
* 3 4 4 3
10+
* But the following [1,2,2,null,3,null,3] is not:
11+
* 1
12+
* / \
13+
* 2 2
14+
* \ \
15+
* 3 3
16+
* <p>
17+
* Note:
18+
* Bonus points if you could solve it both recursively and iteratively.
19+
* <p>
20+
* Created by drfish on 28/05/2017.
21+
*/
22+
public class _101SymmetricTree {
23+
public boolean isSymmetric(TreeNode root) {
24+
if (root == null) {
25+
return true;
26+
}
27+
return check(root.left, root.right);
28+
}
29+
30+
private boolean check(TreeNode p, TreeNode q) {
31+
if (p == null && q == null) {
32+
return true;
33+
}
34+
if (p != null && q != null) {
35+
if (p.val == q.val) {
36+
return check(p.left, q.right) && check(p.right, q.left);
37+
}
38+
}
39+
return false;
40+
}
41+
}

0 commit comments

Comments
 (0)