File tree 2 files changed +70
-0
lines changed
2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change @@ -269,6 +269,7 @@ My accepted leetcode solutions to some of the common interview problems.
269
269
- [ Two Sum IV - Input is a BST] ( problems/src/tree/TwoSumIV.java ) (Easy)
270
270
- [ Average of Levels in Binary Tree] ( problems/src/tree/AverageOfLevelsInBinaryTree.java ) (Easy)
271
271
- [ Convert Binary Search Tree to Sorted Doubly Linked List] ( problems/src/tree/BSTtoDoublyLinkedList.java ) (Easy)
272
+ - [ Same Tree] ( problems/src/tree/SameTree.java ) (Easy)
272
273
273
274
#### [ Two Pointers] ( problems/src/two_pointers )
274
275
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments