-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSymmetricTree.java
More file actions
93 lines (87 loc) · 2.2 KB
/
Copy pathSymmetricTree.java
File metadata and controls
93 lines (87 loc) · 2.2 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package algorithms;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* 101. Symmetric Tree
* https://leetcode.com/problems/symmetric-tree/
* Difficulty : Easy
* Related Topics : Tree, Depth-first Search, Breadth-first Search
*
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
*
* For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
*
* 1
* / \
* 2 2
* / \ / \
* 3 4 4 3
*
*
* But the following [1,2,2,null,3,null,3] is not:
*
* 1
* / \
* 2 2
* \ \
* 3 3
*
*
* 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;
* }
* }
*
*
* created by cenkc on 8/25/2020
*/
public class SymmetricTree {
/**
* Runtime: 2 ms, faster than 10.07% of Java online submissions for Symmetric Tree.
* Memory Usage: 38.6 MB, less than 52.16% of Java online submissions for Symmetric Tree.
*
* @param root
* @return
*/
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
List<List<Integer>> fullList = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root.left);
q.offer(root.right);
while ( ! q.isEmpty()) {
TreeNode left = q.poll();
TreeNode right = q.poll();
if (left == null && right == null) {
continue;
}
if (
(left == null && right != null) ||
(left != null && right == null)) {
return false;
}
if (left.val != right.val) {
return false;
}
// L R
// / \ / \
// 3 4 4 3
q.offer(left.left);
q.offer(right.right);
q.offer(left.right);
q.offer(right.left);
}
return true;
}
}