-
Notifications
You must be signed in to change notification settings - Fork 0
/
101. 对称二叉树.java
72 lines (68 loc) · 2.01 KB
/
101. 对称二叉树.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* 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;
* }
* }
*/
/**
* 递归,O(n), S(n)
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode leftNode, TreeNode rightNode){
if(leftNode == null && rightNode == null){
return true;
}else if(leftNode == null || rightNode == null){
return false;
}else if(leftNode.val != rightNode.val){
return false;
}
return isSymmetric(leftNode.left, rightNode.right) && isSymmetric(leftNode.right, rightNode.left);
}
}
/**
* 迭代,O(n), S(n)
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return isSymmetric(root.left, root.right);
}
private boolean isSymmetric(TreeNode leftNode, TreeNode rightNode){
Queue<TreeNode> treeQueue = new LinkedList<>();
treeQueue.offer(leftNode);
treeQueue.offer(rightNode);
while(!treeQueue.isEmpty()){
TreeNode tempLeft = treeQueue.poll();
TreeNode tempRight = treeQueue.poll();
if(tempLeft == null && tempRight == null){
continue;
}else if(tempLeft == null || tempRight == null){
return false;
}else if(tempLeft.val != tempRight.val){
return false;
}
treeQueue.offer(tempLeft.left);
treeQueue.offer(tempRight.right);
treeQueue.offer(tempLeft.right);
treeQueue.offer(tempRight.left);
}
return true;
}
}