-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSymmetric Tree.java
57 lines (50 loc) · 1.4 KB
/
Symmetric Tree.java
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// recursive solution
public class Solution {
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
return isSameTree(root.left, root.right);
}
private static boolean isSameTree(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.val == right.val) {
return isSameTree(left.left, right.right) &&isSameTree(left.right, right.left);
}
return false;
}
}
// iterative solution
if(root == null) return true;
Queue<TreeNode> leftNodes = new LinkedList<TreeNode>();
Queue<TreeNode> rightNodes = new LinkedList<TreeNode>();
leftNodes.add(root.left);
rightNodes.add(root.right);
while (!leftNodes.isEmpty() && !rightNodes.isEmpty()) {
TreeNode leftNode = leftNodes.poll();
TreeNode rightNode = rightNodes.poll();
if (leftNode == null && rightNode == null) {
continue;
}else if (leftNode == null || rightNode == null ||leftNode.val != rightNode.val) {
return false;
}
leftNodes.add(leftNode.left);
leftNodes.add(leftNode.right);
rightNodes.add(rightNode.right);
rightNodes.add(rightNode.left);
}
return true;