Skip to content

Commit

Permalink
Java solution 100 && 101
Browse files Browse the repository at this point in the history
  • Loading branch information
gavinfish committed May 28, 2017
1 parent 77e5f42 commit 5b0c3f0
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
19 changes: 19 additions & 0 deletions java/_100SameTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Given two binary trees, write a function to check if they are equal or not.
* Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
* <p>
* Created by drfish on 28/05/2017.
*/
public class _100SameTree {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p != null && q != null) {
if (p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
return false;
}
}
41 changes: 41 additions & 0 deletions java/_101SymmetricTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
* <p>
* For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
* But the following [1,2,2,null,3,null,3] is not:
* 1
* / \
* 2 2
* \ \
* 3 3
* <p>
* Note:
* Bonus points if you could solve it both recursively and iteratively.
* <p>
* Created by drfish on 28/05/2017.
*/
public class _101SymmetricTree {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return check(root.left, root.right);
}

private boolean check(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p != null && q != null) {
if (p.val == q.val) {
return check(p.left, q.right) && check(p.right, q.left);
}
}
return false;
}
}

0 comments on commit 5b0c3f0

Please sign in to comment.