-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSymmetricTree.java
More file actions
82 lines (61 loc) · 2.07 KB
/
Copy pathSymmetricTree.java
File metadata and controls
82 lines (61 loc) · 2.07 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
package leetcode.tree;
import static leetcode.util.tree.BinTreeUtil.*;
import java.util.ArrayList;
import java.util.List;
import leetcode.util.tree.TreeNode;
public class SymmetricTree {
// TODO: BFS based solution
// TODO: Full recursive solution
/**
* Solution 1 based on DFS algorithm
*/
public boolean isSymmetric(TreeNode root) {
if (root == null)
return true;
if (root.left != null && root.right != null && root.left.val != root.right.val)
return false;
List<Integer> result = new ArrayList<>();
dfs(root, result);
int size = result.size();
for (int i = 0; i < size / 2; i++) {
if (result.get(i) != result.get(size - i - 1)) {
return false;
}
}
return true;
}
private void dfs(TreeNode root, List<Integer> result) {
if (root == null) {
return;
}
dfs(root.left, result);
if (root.left != null && root.right == null) {
result.add(root.val);
result.add(null);
} else if (root.left == null && root.right != null) {
result.add(null);
result.add(root.val);
} else {
result.add(root.val);
}
dfs(root.right, result);
}
public static void main(String[] args) {
SymmetricTree sln = new SymmetricTree();
TreeNode t1 = initTree(1, 2, 2, 3, 4, 4, 3);
printInorder(t1);
System.out.println(sln.isSymmetric(t1));
TreeNode t2 = initTree(1, 2, 2, null, 3, null, 3);
printInorder(t2);
System.out.println(sln.isSymmetric(t2));
TreeNode t3 = initTree(1, 2, 2, 2, null, 2);
printInorder(t3);
System.out.println(sln.isSymmetric(t3));
TreeNode t4 = initTree(1, 2, 2, null, 3, 3);
printInorder(t4);
System.out.println(sln.isSymmetric(t4));
TreeNode t5 = initTree(5, 4, 1, null, 1, null, 4, 2, null, 2, null);
printInorder(t5);
System.out.println(sln.isSymmetric(t5));
}
}