-
Notifications
You must be signed in to change notification settings - Fork 5
/
SameTree.java
65 lines (61 loc) · 1.99 KB
/
SameTree.java
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
62
63
64
65
/*
Problem Statement:
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Problem Link:
Same Tree: https://leetcode.com/problems/same-tree/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/SameTree.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
return isSameTreeIterative(p, q);
//return isSameTreeRecursive(p, q);
}
public boolean isSameTreeIterative(TreeNode p, TreeNode q) {
Queue<TreeNode> pq = new LinkedList<>();
Queue<TreeNode> qq = new LinkedList<>();
pq.add(p);
qq.add(q);
while(true){
if(pq.isEmpty() && qq.isEmpty()){
return true;
}
if((pq.isEmpty() && !qq.isEmpty()) || (!pq.isEmpty() && qq.isEmpty())){
return false;
}
TreeNode pn = pq.remove();
TreeNode qn = qq.remove();
if((pn!=null && qn==null) || (pn==null && qn!=null)){
return false;
}
if(pn==null && qn==null){
continue;
}
if(pn.val != qn.val){
return false;
}
pq.add(pn.left);
pq.add(pn.right);
qq.add(qn.left);
qq.add(qn.right);
}
}
public boolean isSameTreeRecursive(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}
if((p!=null && q==null) ||
(p==null && q!=null)){
return false;
}
if(p.val != q.val)
return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}