-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsameTree.java
More file actions
88 lines (80 loc) · 2.72 KB
/
sameTree.java
File metadata and controls
88 lines (80 loc) · 2.72 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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
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.
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null)
return true;
if(p == null || q == null)
return false;
678
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
else
return false;
}
}
/* The following Solution comes from Github: Walnutown. */
// Serialize the tree and compare
// time:
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
String sp = getSerialization(p), sq = getSerialization(q);
if (sp.length()!=sq.length())
return false;
for (int i=0; i<sp.length(); i++){
if (sp.charAt(i)!=sq.charAt(i))
return false;
}
return true;
}
StringBuilder sb;
private String getSerialization(TreeNode root){
sb = new StringBuilder();
preorder(root, sb);
return sb.toString();
}
private void preorder(TreeNode node, StringBuilder sb){
if (node==null){
sb.append("#");
return;
}
sb.append(node.val);
preorder(node.left, sb);
preorder(node.right, sb);
}
}
// Tree serialization using level order traversal
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
LinkedList<TreeNode> level1 = new LinkedList<TreeNode>(), level2 = new LinkedList<TreeNode>();
level1.add(p); level2.add(q);
while(!level1.isEmpty() && !level2.isEmpty()) {
LinkedList<TreeNode> temp1 = new LinkedList<TreeNode>(), temp2 = new LinkedList<TreeNode>();
while(!level1.isEmpty() && !level2.isEmpty()) {
TreeNode n1 = level1.poll(), n2 = level2.poll();
if(n1 == null && n2 == null);
else if(n1 == null || n2 == null) return false;
else if(n1.val != n2.val) return false;
if(n1 != null && n2 != null) {
temp1.add(n1.left); temp1.add(n1.right);
temp2.add(n2.left); temp2.add(n2.right);
}
}
if(!level1.isEmpty() || !level2.isEmpty()) return false;
level1 = temp1; level2 = temp2;
}
if(!level1.isEmpty() || !level2.isEmpty()) return false;
return true;
}
}