forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path100_Same_tree
61 lines (54 loc) · 1.54 KB
/
100_Same_tree
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// https://leetcode.com/problems/same-tree/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
// DFS Approach
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return equal(p, q);
}
public boolean equal(TreeNode p, TreeNode q) {
if (p == null && q == null)
return true;
if (p == null || q == null)
return false;
return (p.val == q.val) && equal(p.left, q.left) && equal(p.right, q.right);
}
}
// BFS Approach
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Queue<TreeNode> queue = new LinkedList();
if (p == null && q == null)
return true;
queue.add(p);
queue.add(q);
while (!queue.isEmpty()) {
TreeNode node1 = queue.poll();
TreeNode node2 = queue.poll();
if (node1 == null && node2 == null)
continue;
if (node1 == null || node2 == null)
return false;
if (node1.val != node2.val)
return false;
queue.add(node1.left);
queue.add(node2.left);
queue.add(node1.right);
queue.add(node2.right);
}
return true;
}
}