File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change
1
+ import leetcode_study .TreeNode ;
2
+
3
+ import java .util .AbstractMap ;
4
+ import java .util .Map ;
5
+
6
+ /**
7
+ * <a href="https://leetcode.com/problems/same-tree/description/">week12-1. same-tree</a>
8
+ * <li>Description: Given the roots of two binary trees p and q, check if they are the same or not </li>
9
+ * <li>Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree </li>
10
+ * <li>Time Complexity: O(N), Runtime 0ms </li>
11
+ * <li>Space Complexity: O(N), Memory 41.14MB </li>
12
+ */
13
+ class Solution {
14
+ public boolean isSameTree (TreeNode p , TreeNode q ) {
15
+ Queue <Map .Entry <TreeNode , TreeNode >> queue = new LinkedList <>();
16
+ queue .add (new AbstractMap .SimpleEntry <>(p , q ));
17
+
18
+ while (!queue .isEmpty ()) {
19
+ Map .Entry <TreeNode , TreeNode > nodeMap = queue .poll ();
20
+ TreeNode nodeP = nodeMap .getKey ();
21
+ TreeNode nodeQ = nodeMap .getValue ();
22
+
23
+ if (nodeP == null && nodeQ == null ) {
24
+ continue ;
25
+ }
26
+ if (nodeP == null || nodeQ == null || nodeP .val != nodeQ .val ) {
27
+ return false ;
28
+ }
29
+
30
+ queue .add (new AbstractMap .SimpleEntry <>(nodeP .left , nodeQ .left ));
31
+ queue .add (new AbstractMap .SimpleEntry <>(nodeP .right , nodeQ .right ));
32
+ }
33
+
34
+ return true ;
35
+ }
36
+ }
You can’t perform that action at this time.
0 commit comments