[LeetCode 101] Symmetric Tree
LeetCode 101 (Java)
[Symmetric Tree] 문제 풀이
[LeetCode 101] Symmetric Tree
Description
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example 1
- Input: root = [1,2,2,3,4,4,3]
- Output: true
Example 2
- Input: root = [1,2,2,null,3,null,3]
- Output: false
Constraints
- The number of nodes in the tree is in the range
[1, 1000]. -100 <= Node.val <= 100
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return dfs(root.left, root.right);
}
private boolean dfs(TreeNode root1, TreeNode root2) {
if (root1 == root2) {
return true;
}
if (root1 == null || root2 == null || root1.val != root2.val) {
return false;
}
return dfs(root1.left, root2.right) && dfs(root1.right, root2.left);
}
}
| Runtime | Memory |
|---|---|
| 0 ms | 41.8 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
// store left child value
if (node.left != null) {
ans.add(node.left.val);
q.offer(node.left);
} else {
ans.add(null);
}
// store right child value
if (node.right != null) {
ans.add(node.right.val);
q.offer(node.right);
} else {
ans.add(null);
}
}
// palindrome check
int l = 0;
int r = ans.size() - 1;
while (l < r) {
Integer a = ans.get(l);
Integer b = ans.get(r);
if (a == null && b == null) {
l++;
r--;
continue;
}
if (a == null || b == null || !a.equals(b)) {
return false;
}
l++;
r--;
}
}
return true;
}
}
Reference
- https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0101.Symmetric%20Tree/Solution.java
This post is licensed under CC BY 4.0 by the author.


