Skip to content

Commit 1227586

Browse files
Same Tree : Accepted
1 parent 23c5486 commit 1227586

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ My accepted leetcode solutions to some of the common interview problems.
269269
- [Two Sum IV - Input is a BST](problems/src/tree/TwoSumIV.java) (Easy)
270270
- [Average of Levels in Binary Tree](problems/src/tree/AverageOfLevelsInBinaryTree.java) (Easy)
271271
- [Convert Binary Search Tree to Sorted Doubly Linked List](problems/src/tree/BSTtoDoublyLinkedList.java) (Easy)
272+
- [Same Tree](problems/src/tree/SameTree.java) (Easy)
272273

273274
#### [Two Pointers](problems/src/two_pointers)
274275

problems/src/tree/SameTree.java

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package tree;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 23/01/2018.
5+
* Given two binary trees, write a function to check if they are the same or not.
6+
7+
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
8+
9+
10+
Example 1:
11+
12+
Input: 1 1
13+
/ \ / \
14+
2 3 2 3
15+
16+
[1,2,3], [1,2,3]
17+
18+
Output: true
19+
Example 2:
20+
21+
Input: 1 1
22+
/ \
23+
2 2
24+
25+
[1,2], [1,null,2]
26+
27+
Output: false
28+
Example 3:
29+
30+
Input: 1 1
31+
/ \ / \
32+
2 1 1 2
33+
34+
[1,2,1], [1,1,2]
35+
36+
Output: false
37+
38+
Solution: Do a pre-order traversal of both the trees in parallel and compare each node
39+
*/
40+
public class SameTree {
41+
42+
public class TreeNode {
43+
int val;
44+
TreeNode left;
45+
TreeNode right;
46+
TreeNode(int x) { val = x; }
47+
}
48+
49+
/**
50+
* Main method
51+
* @param args
52+
* @throws Exception
53+
*/
54+
public static void main(String[] args) throws Exception{
55+
56+
}
57+
58+
public boolean isSameTree(TreeNode p, TreeNode q) {
59+
if((p == null && q != null) || (p != null && q == null)) return false;
60+
if(p == null && q == null) return true;
61+
else{
62+
boolean status = isSameTree(p.left, q.left);
63+
if(!status || p.val != q.val){
64+
return false;
65+
}
66+
return isSameTree(p.right, q.right);
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)