-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSameTree.java
More file actions
40 lines (27 loc) · 1.06 KB
/
Copy pathSameTree.java
File metadata and controls
40 lines (27 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Given two binary trees, write a function to check if they are the same or not.
// See: https://leetcode.com/problems/same-tree/
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.*;
import leetcode.util.tree.TreeNode;
public class SameTree {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p != null ^ q != null || p != null && q != null && p.val != q.val) {
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public static void main(String[] args) {
System.out.println(new SameTree().isSameTree(
initTree(1, 2, 3),
initTree(1, 2, 3))); // true
System.out.println(new SameTree().isSameTree(
initTree(1, 2),
initTree(1, null, 2))); // false
System.out.println(new SameTree().isSameTree(
initTree(1, 2, 1),
initTree(1, 1, 2))); // false
}
}