forked from srishilesh/Data-Structure-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101_Symmetric_tree
61 lines (55 loc) · 1.41 KB
/
101_Symmetric_tree
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
// https://leetcode.com/problems/symmetric-tree
// Solution 1
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
public boolean isMirror(TreeNode t1, TreeNode t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
// Solution 2
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(root);
while (!q.isEmpty()) {
TreeNode t1 = q.poll();
TreeNode t2 = q.poll();
if (t1 == null && t2 == null) continue;
if (t1 == null || t2 == null) return false;
if (t1.val != t2.val) return false;
q.add(t1.left);
q.add(t2.right);
q.add(t1.right);
q.add(t2.left);
}
return true;
}
// My approach(Fail)
public boolean isSymmetric(TreeNode root){
inorder(root);
return isPalindrome();
}
public void inorder(TreeNode root){
if(root!=null)
{inorder(root.left);
arr.add(root.val);
inorder(root.right);}
}
public boolean isPalindrome()
{
int start = 0;
int end = arr.size()-1;
while(start!=end)
{
if(arr.get(start)!=arr.get(end))
return false;
start++;
end--;
}
return true;
}
}