Skip to content

Commit 69f4a44

Browse files
committed
feat: same-tree
1 parent 098c1b0 commit 69f4a44

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

same-tree/minji-go.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
}

0 commit comments

Comments
 (0)