-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-101-Symmetric-Tree.java
99 lines (78 loc) · 2.96 KB
/
LeetCode-101-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
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
94
95
96
97
98
99
/*
LeetCode: https://leetcode.com/problems/symmetric-tree/
LintCode: http://www.lintcode.com/problem/symmetric-binary-tree/
JiuZhang: http://www.jiuzhang.com/solutions/symmetric-binary-tree/
ProgramCreek: http://www.programcreek.com/2014/03/leetcode-symmetric-tree-java/
Analysis:
Recursive solution is easy.
Iterative solution is a little complex.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
// 1.DFS. Recursive solution
// public boolean isSymmetric(TreeNode root) {
// if(root == null) return true;
// return isSymmetric(root.left, root.right);
// }
// private boolean isSymmetric(TreeNode left, TreeNode right){
// if(left == null && right == null) return true;
// if(left == null || right == null) return false;
// if(left.val != right.val) return false;
// return isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
// }
// Iterative solution
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Queue<TreeNode> left = new LinkedList<TreeNode>();
Queue<TreeNode> right = new LinkedList<TreeNode>();
left.add(root.left);
right.add(root.right);
while(!left.isEmpty() && !right.isEmpty()){
TreeNode l = left.poll();
TreeNode r = right.poll();
if(l == null && r == null)continue;
if((l == null && r != null) || (l != null && r == null)) return false;
if(l.val != r.val) return false;
left.add(l.left);
left.add(l.right);
right.add(r.right);
right.add(r.left);
}
// Since left queue and right queue have the same size, so at here both of them are empty.
return true;
}
// 3.BFS (similar to inorder traversal)
public boolean isSymmetric(TreeNode root) {
if (root == null) return true;
Stack<TreeNode> lStack = new Stack<>();
Stack<TreeNode> rStack = new Stack<>();
lStack.push(root.left);
rStack.push(root.right);
while(!lStack.isEmpty() && !rStack.isEmpty()) {
TreeNode l = lStack.pop();
TreeNode r = rStack.pop();
if (l == null && r == null) {
// do nothing
} else if (l == null || r == null) {
return false;
} else {
if (l.val != r.val) {
return false;
}
lStack.push(l.left);
rStack.push(r.right);
lStack.push(l.right);
rStack.push(r.left);
}
}
return true;
}
}