Skip to content

Commit eb54d94

Browse files
committed
tree comparison implementation
1 parent 1a02270 commit eb54d94

File tree

3 files changed

+56
-0
lines changed

3 files changed

+56
-0
lines changed

src/dataStructures/linkedLists/middleOfLinkedList/MiddleOfLinkedList.java renamed to src/dataStructures/linkedLists/singleLL/middleOfLinkedList/MiddleOfLinkedList.java

File renamed without changes.

src/dataStructures/linkedLists/middleOfLinkedList/Node.java renamed to src/dataStructures/linkedLists/singleLL/middleOfLinkedList/Node.java

File renamed without changes.
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package dataStructures.trees;
2+
3+
public class TreeComparison {
4+
public static void main(String[] args) {
5+
// setup
6+
TreeNode p = new TreeNode(1, new TreeNode(2), new TreeNode(3));
7+
TreeNode q = new TreeNode(1, new TreeNode(2), new TreeNode(30));
8+
9+
// method
10+
if (isSameTree(p, q)) {
11+
System.out.println("Same");
12+
} else {
13+
System.out.println("Different");
14+
}
15+
}
16+
17+
// Two binary trees are considered the same if
18+
// they are structurally identical,
19+
// and the nodes have the same value
20+
public static boolean isSameTree(TreeNode p, TreeNode q) {
21+
if ((p == null && q != null) || (p != null && q == null)) {
22+
return false;
23+
} // structural difference
24+
25+
if (p == null && q == null) {
26+
return true;
27+
}
28+
29+
if (p.val != q.val) {
30+
return false;
31+
} // value difference
32+
33+
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
34+
}
35+
36+
37+
// Definition for a binary tree node.
38+
public static class TreeNode {
39+
int val;
40+
TreeNode left;
41+
TreeNode right;
42+
43+
TreeNode() {
44+
}
45+
46+
TreeNode(int val) {
47+
this.val = val;
48+
}
49+
50+
TreeNode(int val, TreeNode left, TreeNode right) {
51+
this.val = val;
52+
this.left = left;
53+
this.right = right;
54+
}
55+
}
56+
}

0 commit comments

Comments
 (0)